为什么使用 jQuery 预加载图像的尝试不起作用?
目前我有这段代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果浏览器已缓存图像,则 onload 事件可能不会触发。您可以做的是手动触发已设置
complete
属性的图像的加载事件: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: