【发布时间】:2015-12-15 16:56:33
【问题描述】:
是否可以检测到图像是否已被 jQuery 加载?
【问题讨论】:
标签: jquery image-load
是否可以检测到图像是否已被 jQuery 加载?
【问题讨论】:
标签: jquery image-load
您可以使用.load() 事件处理程序,如下所示:
$("#myImg").load(function() {
alert('I loaded!');
}).attr('src', 'myImage.jpg');
确保在设置源之前附加它,否则事件可能在您附加处理程序以侦听它之前触发(例如从缓存加载)。
如果这不可行(绑定后设置src),请务必检查它是否已加载并自行触发,如下所示:
$("#myImg").load(function() {
alert('I loaded!');
}).each(function() {
if(this.complete) $(this).load();
});
【讨论】:
$("#myImg").live("load", function(){ //dance });"
.load() 自 jQuery v1.8 起已弃用
.load( 替换为 .on('load', 即可获得 1.7+ 中的等效功能。
使用纯 Javascript 一样简单:
// Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
【讨论】:
我也研究了很久,发现这个插件非常棒 帮助解决这个问题:https://github.com/desandro/imagesloaded
这似乎是一大堆代码,但是...我没有找到其他方法来检查图像何时加载。
【讨论】:
使用 jQuery on('load') 函数是检查图像是否加载的正确方法。但请注意,如果图像已经在缓存中,on('load') 函数将不起作用。
var myImage = $('#image_id');
//check if the image is already on cache
if(myImage.prop('complete')){
//codes here
}else{
/* Call the codes/function after the image is loaded */
myImage.on('load',function(){
//codes here
});
}
【讨论】:
使用 jquery 很容易:
$('img').load(function(){
//do something
});
如果尝试过:
$('tag')html().promise().done(function(){
//do something
}) ;
但这不会检查图片是否已加载。如果代码被加载,那场火灾就完成了。否则,您可以检查代码是否完成,然后触发 img 加载功能并检查图片是否真的加载。所以我们将两者结合起来:
$('tag')html('<img src="'+pic+'" />').promise().done(function(){
$('img').load(function(){
//do something like show fadein etc...
});
}) ;
【讨论】:
我觉得这对你有点帮助:
$('img').error(function(){
$(this).attr( src : 'no_img.png');
})
所以,如果它加载 - 将显示原始图像。在其他 - 将显示图像,其中包含崩溃图像或 404 HTTP 标头的事实。
【讨论】: