我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
当前回答
通过使用jQuery生成带有图像src的新图像,并将load方法直接分配给它,当jQuery生成新图像时,load方法将被成功调用。这是为我工作在IE 8, 9和10
$('<img />', {
"src": $("#img").attr("src")
}).load(function(){
// Do something
});
其他回答
你真的必须用jQuery来做吗?你也可以将onload事件直接附加到你的图像上;
<img src="/path/to/image.jpg" onload="doStuff(this);" />
它将在每次图像加载时触发,无论是否从缓存中加载。
你也可以使用这段代码来支持加载错误:
$("img").on('load', function() {
// do stuff on success
})
.on('error', function() {
// do stuff on smth wrong (error 404, etc.)
})
.each(function() {
if(this.complete) {
$(this).load();
} else if(this.error) {
$(this).error();
}
});
通过使用jQuery生成带有图像src的新图像,并将load方法直接分配给它,当jQuery生成新图像时,load方法将被成功调用。这是为我工作在IE 8, 9和10
$('<img />', {
"src": $("#img").attr("src")
}).load(function(){
// Do something
});
我是否可以建议您将其重新加载到非dom图像对象中?如果它被缓存,这将完全不花费时间,onload仍然会触发。如果它没有被缓存,它将在图像加载时触发onload,这应该与图像的DOM版本完成加载的时间相同。
Javascript:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.src = $('#img').attr('src') ;
tmpImg.onload = function() {
// Run onload code.
} ;
}) ;
更新(以处理多个图像和正确顺序的onload附件):
$(document).ready(function() {
var imageLoaded = function() {
// Run onload code.
}
$('#img').each(function() {
var tmpImg = new Image() ;
tmpImg.onload = imageLoaded ;
tmpImg.src = $(this).attr('src') ;
}) ;
}) ;
我找到了一个解决方案https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (此代码直接取自注释)
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;