0

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?

2

3 Answers 3

1
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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome - I'm a little embarrassed I overlooked something this easy. I'll award answer once I have a chance to try it in my code.
Worked like a charm - very detailed answer. Cheers mate.
0

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

Comments

0

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]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.