Search code examples
jqueryimage-preloader

Why does this attempt at preloading images with jQuery not work?


Current I have this code:

var imgCount = 36;
var container = $('#3D-spin');

var loaded = 0;
function onLoad()
{
    alert(loaded);
    loaded++;
    if(loaded >= imgCount)
    {
        alert('yay');
    }
}

for(var i = imgCount-1; i >= 0; i--)
{
    container.prepend(
        $('<img>')
            .one('load', onLoad)
            .attr('alt', 'View from '+(i*360/imgCount)+'\u00B0')
            .attr('src', '/images/3d-spin/robot ('+i+').jpg')
    );
}

However, it's behaving VERY strangely. Normally, I get no alert boxes. However, if I open developer tools, and pause script execution, I get a single alert that says 0. There's nothign like a good old heisenbug!

A live example can be found here. The script itself is called style.js, and it is clear that images have loaded.

Am I doing something stupidly, or is jQuery playing up?


Solution

  • If the images have been cached by the browser, there's a chance that the onload event will not fire. What you can do is manually fire the load event for images that have their complete property set:

    container.prepend(
        $('<img>')
            .one('load', onLoad)
            .attr('alt', 'View from '+(i*360/imgCount)+'\u00B0')
            .attr('src', '/images/3d-spin/robot ('+i+').jpg')
            .each(function() { if(this.complete) $(this).trigger("load"); }
        );