@alex写的插件由于某种原因不适合我......我找不出原因。但他的代码确实激励我想出一个更适合我的更轻量级的解决方案。它使用jQuery的承诺。请注意,与@alex的插件不同,这不会试图解释元素上的背景图像,只是img元素。
// Fn to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function() {
// get all the images (excluding those with no src attribute)
var $imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred().resolve().promise();}
// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.onerror = function(){dfd.resolve();}
img.src = this.src;
});
// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($,dfds);
}
然后你可以使用它是这样的:
$.ajax({
cache: false,
url: 'ajax/content.php',
success: function(data) {
$('#divajax').html(data).imagesLoaded().then(function(){
// do stuff after images are loaded here
});
}
});
希望这对别人有帮助的。
请注意,使用上面的代码,如果其中一个图像错误(例如,由于URL错误),承诺无论如何解决,错误被忽略。这可能是你想要的,但是,根据你的情况,如果图片加载失败,你可能会想放弃你正在做的任何事情。在这种情况下,可以按如下方式更换的onerror行:
img.onerror = function(){dfd.reject();}
,赶上这样的错误:
$('#divajax').html(data).imagesLoaded().done(function(){
// do stuff after all images are loaded successfully here
}).fail(function(){
// do stuff if any one of the images fails to load
});
事情是我不能关闭异步调用带有负荷和设置缓存选项权利? – robs 2011-01-23 16:27:31