[英]Cross-browser solution for a callback when loading multiple images?
I checked other questions, but they all had information how to make a callback when one specific image has loaded: 我检查了其他问题,但是他们都有关于如何在加载一个特定图像时进行回调的信息:
var img = new Image();
img.src = "images/img.png";
if (!img.complete) {
img.onload = function() {
// code to be executed when the image loads
}
}
Or a simple check to see if all images are loaded with an 'if' statement. 或者,只需检查是否所有图像都加载了“if”语句。 Also, $(window).load (or onLoad or whatever) doesn't work.
此外,$(window).load(或onLoad或其他)不起作用。
In my case I'm loading two images: 在我的情况下,我正在加载两个图像:
var img1 = new Image();
var img2 = new Image();
img1.src = 'images/img1.png';
img2.src = 'images/img2.png';
How can I define a callback similar to the one in the first example, but it gets executed when BOTH images have finished loading? 如何定义类似于第一个示例中的回调,但是当两个图像完成加载时它会被执行?
Thank you for your time. 感谢您的时间。
Here's a function that will create several images and call a callback when they are all loaded: 这是一个函数,它将创建多个图像并在它们全部加载时调用回调:
function createImages(srcs, fn) {
var imgs = [], img;
var remaining = srcs.length;
for (var i = 0; i < srcs.length; i++) {
img = new Image();
imgs.push(img);
img.onload = function() {
--remaining;
if (remaining == 0) {
fn(srcs);
}
};
img.src = srcs[i];
}
return(imgs);
}
var imgs = createImages(['images/img1.png', 'images/img2.png'], myCallback);
PS whenever working with .onload
for images, you must set the .onload
handler before setting the .src
value because the onload handler might fire immediately when setting the .src value if the image is in the cache. PS每当使用
.onload
进行映像时,必须在设置.src
值之前设置.onload
处理程序,因为如果映像位于缓存中,则在设置.src值时可能会立即触发onload处理程序。 If you haven't set the onload handler first, then it may never fire because by the time you set the handler, the image is already loaded. 如果您尚未首先设置onload处理程序,那么它可能永远不会触发,因为在您设置处理程序时,图像已经加载。 This happens in some browsers.
这在某些浏览器中会发生。 Just always set
.onload
before .src
if you need the onload event. 如果需要onload事件,只需在
.onload
之前设置.onload
.src
。
It's called reference counting. 它被称为引用计数。 It's the standard technique for running a single callback after n tasks have finished.
这是n个任务完成后运行单个回调的标准技术。
var count = 2;
img1.onload = function () {
count-- === 0 && callback();
}
img2.onload = function () {
count-- === 0 && callback();
}
function callback() {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.