Question

Working on an HTML5/CSS3 project that requires some mildly large (~100k) sprite maps to be loaded and placed onto a <canvas>. The placement is no problem, but I'm running into the problem of accidentally place the images before they're loaded, because there's no way to detect load completion of images requested via javascript.

What's the best way to preload images and get a handle on the oncomplete event? Right now I'm detecting pageload with the standard $(document).ready(), but I can adapt the code to any event handler required. If there's a plugin that handles it all, then brilliant.

I'm a little more particular about the preloading though - if possible I'd like everything to stay inside javascript. Looking for something more elegant than placing the images in a hidden div or dummy css.

Any ideas?

Was it helpful?

Solution

var img = new Image();
img.onload = callbackFunction;
img.src = 'http://source.of/image.png';

If you use this a lot, just create a function for it:

function preloadImage (src, callback) {
    var img = new Image();
    img.onload = callback;
    img.src = src;
    return img;
}

If you want to fire a callback when all the images have loaded, use a deferred object:

function preloadImages (paths, callback) {

    var deferreds = [];

    $.each(paths, function (i, src) {
        var deferred = $.Deferred(),
            img = new Image();

        deferreds.push(deferred);
        img.onload = deferred.resolve;
        img.src = src;
    });

    $.when.apply($, deferreds).then(callback);
}

OTHER TIPS

Can you use the load handler? http://api.jquery.com/load-event/

You can preload multiple images and assign the same or different callbacks to each like this:

preloadImages([
    {src:"image1.jpg", callback:someFunction1},
    {src:"image2.jpg", callback:someFunction2},
    {src:"image3.jpg", callback:someFunction3}
]);

function preloadImages(arr)
{   
    function _preload(imgObj)
    {
        var img = new Image();
        img.src = imgObj.src;
        img.onload = imgObj.callback;
    }

    for (var i = 0; i < arr.length; i++)
    {
        _preload(arr[i]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top