如何判断图像是否在JQuery中加载或缓存?
问题描述:
似乎.load()函数在图像先前被缓存时不会触发。所以,如果你想确保一个图像已经加载和显示其它(即放大镜)之前加载,你不能这样做:如何判断图像是否在JQuery中加载或缓存?
$(img_to_load_first)
.load(
$(img_to_load_last)
.src("2nd.png");
)
.src("1st.png");
那么,如何确保JQuery的加载顺序?
答
你需要做的是有选择地处理你的加载绑定。您可以通过测试图像对象属性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提供的图像对象。
答
谢谢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
});
});
这几乎可以归结为你所说的,只有他完成的检查也测试“未定义”。
答
如果你想换行所有这些功能在一个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");
});
答
你也可以检查你的图像是否有宽度或高度来检测它是否已经加载。
例如:
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');
});
}
当这个码被运行?它在$(document).ready中吗? – 2009-12-22 19:50:08