检测图像加载

56

使用jQuery可以检测图片何时加载完毕吗?

6个回答

106

您可以使用.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(){ //跳舞 });" - Erik Escobedo
6
很抱歉,.load() 方法自 jQuery v1.8 版本起已被弃用。 - SquareCat
29
由于事件处理器和 AJAX 内容获取器之间的歧义,该功能已被弃用。在上述代码中,只需将 .load( 替换为 .on('load',,即可在 1.7+ 版本中实现等效功能。 - Nick Craver
1
我已经为此苦思冥想了几个小时。感谢@NickCraver。我们有一个广告图像,它是从广告服务器动态加载的,所以我们无法控制。我能够使用这个来测试它是否正确加载,因此我可以使用JS将其水平/垂直居中。 - Markus
1
嗨,Nick,这个程序在跨浏览器兼容方面如何?能够可靠地在IE8、IE9上工作吗?其次,如果图像从浏览器缓存中立即加载,处理程序是否会触发? - SexyBeast
我曾经可以在页面加载期间的任何时候运行$("#myImg").on('load',,但现在在Google Chrome中,我必须在$(document).on('ready',内调用它才能每次正确触发。我还在图像源上放置了一个动态查询字符串,以使其更可靠。它似乎有点出问题。<img src="pic.jpg?<?php echo time(); ?>"> - Ben Sinclair

21

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

4
检查已经在缓存中的图像时,这种方法会失败。 - vsync

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

6

我也一直在研究这个问题,发现这个插件非常有帮助:https://github.com/desandro/imagesloaded

看起来代码很复杂,但是我没有找到其他检查图像加载状态的方法。


1
很容易使用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...
   });
}) ;

0

我认为这可以帮助你一点:

    $('img').error(function(){
        $(this).attr( src : 'no_img.png');
 })

所以,如果它被加载 - 将显示原始图像。否则 - 将显示包含崩溃图像或404 HTTP头的事实的图像。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接