How to load html page and content (like images) in jQuery?

In jQuery, I know that I can use the $ .ajax function to load an html page from a given URL. However, I am interested in downloading htmla and all the resources on this page before displaying it. How should I do it?

Example: Say I have the following html in a file called about.html

<h1>About BigImage</h1>
<img src="/images/reallybigimage.jpg" />

Please note that I have an image on this page. Using the jQuery ajax function, I would get "success" as soon as the HTML finished loading, but not the image.

Here, for example, is a kicker: I don’t know how many / which images I will have on the page, and these are not only the images I want to upload - all the resources of the page are css and that's it. Any way to do this?

Thank!

+3
source share
4 answers

If relative paths are not a problem, in your function successyou can try to find all the links and load them as follows:

//....
success:function(data){
    $("*",data).each(function(){
        if($(this).attr("src")){
            $.ajax({url:$(this).attr("src"),dataType:"text"});
        }
        if($(this).attr("href")){
            $.ajax({url:$(this).attr("href"),dataType:"text"});
        }
    });
}
//....
+1
source

In the success callback, convert the html to a document fragment, then select the fragments you want to preload and preload. I will not include the code for the actual preload, because it should be a question about this, and there are plugins that already exist to do just that.

$.ajax(options).done(function(html){
    var $html = $(html),
        imgArr = $.map($html.find("img"),function(img) {
           return this.src;
        }),
        cssArr = $.map($html.find("link"),function(link) {
           return this.href;
        });
    // loop through and preload images and css.
    ...
    // once all are done loading, append to page.
    $("#content").html($html);
});

You do not need to preload the scripts, however you can detach them and add them to the body after adding the contents.

+3
source

, ( ). , .

, , RegExp, /<img[^>]*src(["'])([^"']+)\1[^>]*>/g. catching, function (a, q, src){var i = new Image(src)}.

You can also attach the downloaded document fragment to the DOM document fragment and work with it using the DOM. This may consume more resources.

+1
source

Are you looking for this?

 $("body").load("page.html")

(edit :) Or do you want to save pagecontent in a variable? This is possible with $ .ajax:

     $.ajax({
      url: "page.html",
      dataType: 'html',
      success: function(data) {
var pagecontents = data;

}
    });
0
source

All Articles