Jquery 检测图像负载

Jquery 检测图像负载,jquery,image-load,Jquery,Image Load,使用jQuery加载图像后是否可以检测?您可以使用事件处理程序,如下所示: $("#myImg").load(function() { alert('I loaded!'); }).attr('src', 'myImage.jpg'); $("#myImg").load(function() { alert('I loaded!'); }).each(function() { if(this.complete) $(this).load(); }); 请确保在设置源之前附加它,否

使用jQuery加载图像后是否可以检测?

您可以使用事件处理程序,如下所示:

$("#myImg").load(function() {
  alert('I loaded!');
}).attr('src', 'myImage.jpg');
$("#myImg").load(function() {
  alert('I loaded!');
}).each(function() {
  if(this.complete) $(this).load();
});
请确保在设置源之前附加它,否则在附加处理程序以侦听它之前(例如,从缓存加载)可能已触发事件

如果这不可行(在绑定后设置
src
),请确保检查它是否已加载并自己启动,如下所示:

$("#myImg").load(function() {
  alert('I loaded!');
}).attr('src', 'myImage.jpg');
$("#myImg").load(function() {
  alert('I loaded!');
}).each(function() {
  if(this.complete) $(this).load();
});

使用纯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;

我也一直在研究这个很长时间,并发现这个插件非常棒 这方面的帮助:

这似乎是一堆令人敬畏的代码,但是……我没有找到其他方法来检查图像是否已加载。

使用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
     });
}

我想这可以帮你一点忙:

    $('img').error(function(){
        $(this).attr( src : 'no_img.png');
 })
所以,如果它加载-将显示原始图像。在other中-将显示包含崩溃图像或404 HTTP头的事实的图像。

使用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...
   });
}) ;
$('tag')html(“”).promise().done(函数(){
$('img').load(函数(){
//做一些像秀法登等。。。
});
}) ;

是否可以这样做:
$(“#myImg”).live(“load”,function(){//dance})“不幸的是,
.load()
从jqueryv1开始就被弃用了。8@CummanderCheckov由于事件处理程序和ajax内容获取程序之间的不确定性,它被弃用。在上面的代码中,只需将
.load(
替换为
.on)('load',
,用于1.7+中的等效功能。我已经花了好几个小时在这上面了。谢谢@NickCraver。我们有一个从广告服务器动态加载的广告图像,所以我们这边没有控制。我可以用它来测试它是否正确加载,所以我可以使用JS将其居中horz/vert.Hi Nick,跨浏览器兼容程度如何这是否可靠地在IE8、IE9上工作?其次,如果从浏览器缓存中立即加载图像,处理程序是否会启动?在检查缓存中已有的图像时,这会失败。