我想做的是:

$("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);" />

它将在每次图像加载时触发,无论是否从缓存中加载。

如果src已经设置,则在绑定事件处理程序之前,事件就会在缓存的情况下触发。为了解决这个问题,你可以循环检查和触发基于.complete的事件,就像这样:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) {
      $(this).load(); // For jQuery < 3.0 
      // $(this).trigger('load'); // For jQuery >= 3.0 
  }
});

注意从.bind()到.one()的变化,因此事件处理程序不会运行两次。

对GUS示例的修改:

$(document).ready(function() {
    var tmpImg = new Image() ;
    tmpImg.onload = function() {
        // Run onload code.
    } ;

tmpImg.src = $('#img').attr('src');
})

在onload之前和之后设置源。

你也可以使用这段代码来支持加载错误:

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

你可以使用JAIL插件来解决这个问题,它还允许你延迟加载图像(提高页面性能)并将回调作为参数传递

$('img').asynchImageLoader({callback : function(){...}});

HTML应该是这样的

<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />