加载多个图像时回调的跨浏览器解决方案? [英] Cross-browser solution for a callback when loading multiple images?

查看:53
本文介绍了加载多个图像时回调的跨浏览器解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了其他问题,但他们都提供了在加载特定图像时如何进行回调的信息:

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
    }
}

或者简单检查一下是否所有图像都加载了if"语句.此外,$(window).load(或 onLoad 或其他)不起作用.

Or a simple check to see if all images are loaded with an 'if' statement. Also, $(window).load (or onLoad or whatever) doesn't work.

就我而言,我正在加载两个图像:

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?

感谢您的宝贵时间.

推荐答案

这是一个创建多个图像并在它们全部加载时调用回调的函数:

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

附言每当使用 .onload 处理图像时,您必须在设置 .src 值之前设置 .onload 处理程序,因为 onload 处理程序可能会在以下情况下立即触发如果图像在缓存中,则设置 .src 值.如果您没有先设置 onload 处理程序,那么它可能永远不会触发,因为在您设置处理程序时,图像已经加载.这发生在某些浏览器中.如果需要 onload 事件,请始终在 .src 之前设置 .onload.

P.S. 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. 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. This happens in some browsers. Just always set .onload before .src if you need the onload event.

这篇关于加载多个图像时回调的跨浏览器解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆