2009-12-22 98 views
6

似乎.load()函数在图像先前被缓存时不会触发。所以,如果你想确保一个图像已经加载和显示其它(即放大镜)之前加载,你不能这样做:如何判断图像是否在JQuery中加载或缓存?

$(img_to_load_first) 
    .load(
     $(img_to_load_last) 
      .src("2nd.png"); 
    ) 
    .src("1st.png"); 

那么,如何确保JQuery的加载顺序?

+0

当这个码被运行?它在$(document).ready中吗? – 2009-12-22 19:50:08

回答

14

你需要做的是有选择地处理你的加载绑定。您可以通过测试图像对象属性complete来验证加载。

例如:

$('.load_selector').each(function(){ 

    if (!this.complete) { 
     $(this).load(function(){ 
      // handle image load event binding here 
     }); 
    } else { 
     // handle image already loaded case 
    } 

}); 

注意,以上,this(单独使用)指的是DOM引用的jQuery提供的图像对象。

+0

这对您有帮助吗?请注意,如果需要,您可以像上面那样在'else'子句中触发您的装载处理程序。 – sparkey0 2009-12-22 22:02:39

+0

关于兼容性的任何想法? – 2017-01-31 15:45:39

+1

广泛的支持,请参阅浏览器矩阵在这里:http://www.w3schools.com/jsref/prop_img_complete.asp - 要记住的一件事是,你可能想检查一个有效的src属性之前检查完整的属性。许多浏览器将返回空的src(例如:空源是完整的,因为它没有加载/将不会加载) – sparkey0 2017-02-06 17:39:16

1

谢谢Sparkey,

我会给这个尝试,但它看起来不错。我发现在话题在这里一个广泛的讨论:这使我的“jQuery的‘onImagesLoad’插件”这里http://www.bennadel.com/blog/1007-jQuery-Attr-Function-Doesn-t-Work-With-IMAGE-complete.htm

http://includes.cirkuit.net/includes/js/jquery/plugins/onImagesLoad/1.1/documentation/

这似乎解决了这个问题,像这样:

$imgs.each(function(i, val){ 
    $(this).bind('load', function(){ 
     // ... 
    }).each(function(){ 
     if (this.complete || this.complete === undefined){ this.src = this.src; } //needed for potential cached images 
    }); 
}); 

这几乎可以归结为你所说的,只有他完成的检查也测试“未定义”。

1

如果你想换行所有这些功能在一个jQuery的扩展方法,尝试的(这应该工作等待任意数量的图像):

$.fn.imagesLoaded = function() { 
    var def = $.Deferred(); 
    var count = this.length; 
    this.each(function() { 
     if (this.complete) { 
      if (!--count) { 
       def.resolve(); 
      } 
     } else { 
      $(this).load(function() { 
       if (!--count) { 
        def.resolve(); 
       } 
      }); 
     } 
    }); 
    return def.promise(); 
} 

,然后简单地使用这样的:

$(img_to_load_first).imagesLoaded().done(function() { 
    $(img_to_load_last).src("2nd.png"); 
}); 
0

你也可以检查你的图像是否有宽度或高度来检测它是否已经加载。

例如:

var img = _content.find('img'); 
    if(img[0].width >0 || img[0].height > 0) { 
    console.log('already loaded image'); 
    } else { 
    img.on('load', function() { 
    console.log('image loaded'); 
    }); 
} 
相关问题