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

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

问题描述

我检查了其他问题,但他们都有一些信息如何在一个特定的图片加载回调:

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

如何定义一个类似于第一个例子中的回调,但是当BOTH图片已经完成加载?

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 图像时,必须先设置 .onload 处理程序,然后再设置 .src 值,因为如果图像在缓存中,则设置.src值时,onload处理程序可能立即触发。如果您尚未设置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天全站免登陆