如何判断图像是否在JQuery中加载或缓存?

似乎.load()函数在之前已缓存图像时不会触发。 因此,如果您想在加载并显示另一个图像(即放大镜)之前确保已加载一个图像,则无法执行以下操作:

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

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

您需要做的是有选择地处理您的加载绑定。 您可以通过测试Image对象属性complete来validation负载。

例如:

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

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

如果你想在jQuery扩展方法中包含所有这些function,试试这个(它应该等待任意数量的图像):

 $.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"); }); 

谢谢Sparkey,

我会尝试一下,但看起来不错。 我在这里找到了关于这个主题的广泛讨论: http : //www.bennadel.com/blog/1007-jQuery-Attr-Function-Doesn-t-Work-With-IMAGE-complete.htm

这导致我在这里找到“jQuery’onImagesLoad’插件”: 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 }); }); 

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

您还可以检查图像是否具有宽度或高度,以检测其是否已加载。

例如:

 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'); }); }