为什么使用 jQuery 预加载图像的尝试不起作用?

发布于 2024-09-06 12:20:21 字数 774 浏览 4 评论 0原文

目前我有这段代码:

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

但是,它的行为非常奇怪。通常情况下,我不会收到警报框。但是,如果我打开开发人员工具并暂停脚本执行,我会收到一条显示 0 的警报。没有什么比老海森虫更好的了!

可以在此处找到一个实例。该脚本本身名为 style.js,很明显图像已加载。

我是在做一些愚蠢的事情,还是 jQuery 正在发挥作用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寒冷纷飞旳雪 2024-09-13 12:20:21

如果浏览器已缓存图像,则 onload 事件可能不会触发。您可以做的是手动触发已设置 complete 属性的图像的加载事件:

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

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"); }
    );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文