加载所有图像后的jquery事件(包括缓存图像)?

我有以下function,用于在页面中进行ajaxing,并且只在加载所有图像后显示它:

$.get('target-page.php', function(data){ var $live = $('#preview_temp_holder').html(data); var imgCount = $live.find('img').length; $('img',$live).load(function(){ imgCount--; if (imgCount==0){ //DO STUFF HERE ONCE ALL IMAGES ARE LOADED $('#preview_pane').html($live.children()).fadeIn(800); $live.children().remove(); } }); }); 

问题是缓存的图像没有触发.load()事件,因此不会减少imgCount

我知道我需要实施Nick Craver的解决方案但不确定如何。 谁能帮我?

我花了很长时间为此寻找解决方案。 jQuery API页面(https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js)上建议的插件在firefox中不起作用。

我的解决方案是循环遍历每个图像,只添加加载事件(如果它尚未加载(即由浏览器缓存))。 下面的代码包括一个计数器,我用它来检查加载事件是否仅针对缓存中尚未存在的图像触发:

 $(document).ready(function () { var images = $("img.lazy"); $(".image-wrapper").addClass("loading"); var loadedCount = 0; images .hide() .each(function () { if (!this.complete) { $(this).load(function () { loadedCount++; console.log(loadedCount); displayImage(this); }); } else { displayImage(this); } }); }); function displayImage(img) { $(img).fadeIn(300, function () { $(this).parents(".image_wrapper").removeClass("loading"); }); } 

我不是javascript专家,所以如果您发现此解决方案的任何问题,请告诉我。 正如我所说,它适用于IE8,Chrome和Firefox(不确定IE的旧版本)。

好的,设法让它们合并:

 $.get('target-page.php', function(data){ var $live = $('#preview_temp_holder').html(data); var $imgs = $live.find('img') var imgCount = $imgs.length; $imgs.one('load', function() { imgCount--; if (imgCount==0){ //DO STUFF HERE //ALL IMAGES ARE LOADED $('#preview_pane').html($live.children()).fadeIn(800); } }) .each(function() { if(this.complete){ $(this).load(); } }); }); 

注意:404图像会打破这个。

更改:

 $('img',$live).one('load', function(){ ... }); 

并在上述追加之后:

 $live.find('img').each(function() { if(this.complete) $(this).load(); }); 

通常我建议从以前的count语句中重用$live.find('img')