为什么这种用jQuery预加载图像的尝试不起作用? [英] Why does this attempt at preloading images with jQuery not work?
问题描述
当前,我有以下代码:
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')
);
}
但是,它的行为非常奇怪.通常,我会收到 no 警报框.但是,如果我打开开发人员工具并暂停脚本执行,则会收到一个警告,提示0
.没什么好像一个老旧的黑松子!
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!
可以在此处找到一个在线示例.该脚本本身称为style.js
,很明显,图像已加载.
A live example can be found here. The script itself is called style.js
, and it is clear that images have loaded.
我是在愚蠢地做某事,还是jQuery正在播放?
Am I doing something stupidly, or is jQuery playing up?
推荐答案
如果浏览器已缓存了图像,则有可能不会触发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:
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"); }
);
这篇关于为什么这种用jQuery预加载图像的尝试不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!