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

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2010-06-17T12:48:44Z Indexed on 2010/06/17 12:53 UTC
Read the original article Hit count: 287

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about image-preloader