@alex编写的插件由于某些原因对我不起作用…我不知道为什么。但是他的代码确实鼓舞了我想出一个对我有用的更轻量级的解决方案。它使用jQuery
Promise。请注意,与@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});


