预加载图像后触发事件 [英] Fire an event after preloading images

查看:73
本文介绍了预加载图像后触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来预加载图片的代码,我不确定它是否是最好的。
我的问题是,如何触发和事件,例如alert();对话框已经完成加载所有图像?

This is the code I use to preload images, I'm not sure if it's the best one. My question is, how can I fire and event, for an example alert(); dialog after is has finished loading all the images?

var preload = ["a.gif", "b.gif", "c.gif"];
    var images = [];
    for (i = 0; i < preload.length; i++) {
        images[i] = new Image();
        images[i].src = preload[i];
    }


推荐答案

你可以使用新的 $ .Deferred如果你愿意:

You can use the new "$.Deferred" if you like:

var preload = ["a.gif", "b.gif", "c.gif"];
var promises = [];
for (var i = 0; i < preload.length; i++) {
    (function(url, promise) {
        var img = new Image();
        img.onload = function() {
          promise.resolve();
        };
        img.src = url;
    })(preload[i], promises[i] = $.Deferred());
}
$.when.apply($, promises).done(function() {
  alert("All images ready sir!");
});

让图像对象漂浮在周围可能有点风险,但如果是这样可以轻松修复通过移动关闭。 编辑其实我会自己更改它,因为它让我烦恼: - )

Might be a little risky to leave the Image objects floating around, but if so that could be fixed easily by shifting the closure. edit in fact I'll change it myself because it's bugging me :-)

这篇关于预加载图像后触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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