daveycroqet
daveycroqet

Reputation: 2727

Preloading images with AJAX for AJAX

My site structure is sequential (as in page1.html leads to page2.html, page2.html leads to page3.html, etc.). I'm wanting to preload some images from the third page on the second page. I've found this wonderful bit of code here on SO:

$.ajax({
    url      : 'somePage.html',  
    dataType : "html",
    success  : function(data) {

        $(data).hide().appendTo('#someDiv');

        var imagesCount = $('#someDiv').find('img').length;
        var imagesLoaded = 0;

        $('#someDiv').find('img').load( function() {
            ++imagesLoaded;
            if (imagesLoaded >= imagesCount) {
                $('#someDiv').children().show();
            }
        });

        var timeout = setTimeout(function() {
            $('#someDiv').children().show();
        }, 5000);
    }                     
});

It works beautifully at dumping the entire contents of page3.html onto page2.html. The problem is, I don't want the entire contents; I just want the images, and I want them hidden and ready for when the user actually loads page3.html. The above snippet brings audio and, well, everything else along with it. So my question is, will this hacked up version below work for my purposes?

$.ajax({
    url      : 'page3.html',  
    dataType : "html",
    success  : function(data) {

        var imagesCount = $(data).find('img').length;
        var imagesLoaded = 0;

        $(data).find('img').load( function() {
            ++imagesLoaded;
            if (imagesLoaded >= imagesCount) {
              //halt? do something?
            }
        });

    }                     
});

Again, all I want is for page3.html's images to be preloaded on page2.html. Will this do the trick? And how can I test to verify?

Upvotes: 0

Views: 188

Answers (1)

Charlie74
Charlie74

Reputation: 2903

I believe the simplest way, in your case, is just to use jQuery.get and specify the images (or any other objects) you want to preload.

For example,

$.get('images/image1.jpg');
$.get('images/image2.jpg');
// etc

This way, you can specify which images from the next page you want to preload in the browser.

The $.get function is just an abbreviated version of the $.ajax function. In your case, you just want to "get" the images so that they are in the browser's cache, so that when you get to the next html page, the images are already loaded.

How to verify

If you were to add the sample code above to your page2, then visit that page while having the Network tab open in Firebug, or Chrome dev tools, you'll see that GET requests are sent for the images and they are loaded to the browser's cache.

Upvotes: 1

Related Questions