我有以下功能,用于在页面中进行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's solution,但不知道如何实施。谁能帮我?
答案 0 :(得分:3)
我花了很长时间寻找解决方案。 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的旧版本)。
答案 1 :(得分:2)
好的,设法将它们合并:
$.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图像会打破这个。
答案 2 :(得分:0)
变化:
$('img',$live).one('load', function(){
...
});
以上追加:
$live.find('img').each(function() {
if(this.complete) $(this).load();
});
通常我建议重复使用之前计数语句中的$live.find('img')
。