Why does this attempt at preloading images with jQuery not work?
- by Eric
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?