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

隐身守侯 提交于 2020-01-02 07:57:11

问题


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:


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


来源:https://stackoverflow.com/questions/3061706/why-does-this-attempt-at-preloading-images-with-jquery-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!