检测图像负载

Pab*_*blo 55 jquery image-load

一旦图像加载了jQuery,是否可以检测到?

Nic*_*ver 107

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

$("#myImg").load(function() {
  alert('I loaded!');
}).attr('src', 'myImage.jpg');
Run Code Online (Sandbox Code Playgroud)

确保设置源之前附加它,或者在附加处理程序以侦听它之前事件可能已被触发(例如从缓存加载).

如果这是不是可行的(设置src绑定后),一定要检查它的加载和启动它自己,是这样的:

$("#myImg").load(function() {
  alert('I loaded!');
}).each(function() {
  if(this.complete) $(this).load();
});
Run Code Online (Sandbox Code Playgroud)

  • @CummanderCheckov由于事件处理程序和ajax内容提取程序之间的歧义而被弃用.在上面的代码中只需替换`.load(`````'('load',`用于1.7+中的等效功能. (26认同)
  • 不幸的是,从.jQuery v1.8开始,不推荐使用`.load()` (4认同)

Pet*_*tai 18

使用普通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;
Run Code Online (Sandbox Code Playgroud)

  • 检查已在缓存中的图像时,这会失败. (3认同)

vsy*_*ync 5

我也一直在研究这个很长时间,并发现这个插件可以很好地帮助解决这个问题:https : //github.com/desandro/imagesloaded

这似乎是一大堆代码,但是......我没有找到其他方法来检查图像何时加载。


jro*_*web 5

使用 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
     });
}
Run Code Online (Sandbox Code Playgroud)