Best way to pre load images


I have a single img tag on my page which is fed different sources from this array:

    preload_image_object = new Image();
    var images = new Array();
    images[0] = "images/01.jpg";
    images[1] = "images/02.jpg";
    images[2] = "images/03.jpg";
    images[3] = "images/04.jpg";
    images[4] = "images/05.jpg";

    //Preload images for faster page response
    for (var i=0; i < images.length; i++) {
        preload_image_object.src = images[i];
    };

I only display one image at a time but I find they are quite large (a few megs each). I need these to load initially so that when I go to the next image it will just appear. Currently there is a slight delay on the iPad I am developing this for.

What would be the best way to preload these images?

Thanks!

Here's a short function in one of my previous answers to preload a number of images: Is there a way to load images to user's cache asynchronously? and a little more advanced version that offers a callback when all images are preloaded: Image preloader javascript that supports events.


You could try a pure CSS image preload:

body:after {
  content: url("images/01.jpg") url("images/02.jpg");
  display: none;
}

Any form of preloading an image will use the same method, as yours and the one from jfriend00. Even using jquery does the same thing.

You could optimise the loop (catch the length of the array etc) but its a small saving.

You would see more noticeable optimising the images them selves

Are CSS sprites an option?


Use this. ask if something you dont understand.

jQuery(document).ready(function () {           
    preload([
        'path to img 1',
        'path to img 2',
        .... array of all images

    ]);

    function preload(images) {
        if (typeof document.body == "undefined") return;
        try {    
            var div = document.createElement("div");
            var s = div.style;
            s.position = "absolute";
            s.top = s.left = 0;
            s.visibility = "hidden";
            document.body.appendChild(div);
            div.innerHTML = "<img src=\"" + images.join("\" /><img src=\"") + "\" />";
            var lastImg = div.lastChild;
            lastImg.onload = function () {
                document.body.removeChild(document.body.lastChild);
            };
        }
        catch (e) {
            // Error. Do nothing.
        }
    }
});