Why does this attempt at preloading images with jQ

2019-05-17 21:38发布

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?

1条回答
乱世女痞
2楼-- · 2019-05-17 22:40

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"); }
    );
查看更多
登录 后发表回答