jQuery或Javascript检查图像是否已加载

我知道Stackoverflow上有很多这些,但我没有找到一个适用于我最近版本的jquery(1.10.2)。

我试过了:

$(".lazy").load(function (){}

但我相信经过一些研究使用.load来检测图像加载在jQuery 1.8中已被弃用。 我需要做的是在加载图像后启动图像resizefunction。 我无法控制HTML,目前我必须通过在页面加载后附加一个属性(通过.attr() )来添加图像尺寸,以便我可以使用lazyload js。

问题是我需要一种准确的方法来阻止我的各种脚本,直到图像正确加载,否则函数有时会在每个图像加载之前触发。 我尝试过使用$(window).load(function (){}); 但是在每张图片加载之前它有时仍然会闪光。

我经常这样做:

 var image = new Image(); image.onload = function () { console.info("Image loaded !"); //do somethinghttps://stackoverflow.com/questions/20613984/jquery-or-javascript-check-if-image-loaded/... } image.onerror = function () { console.error("Cannot load image"); //do something elsehttps://stackoverflow.com/questions/20613984/jquery-or-javascript-check-if-image-loaded/... } image.src = "/images/blah/foo.jpg"; 

请记住,加载是异步的,因此您必须在onloadonerror事件中继续执行脚本。

还有一个有用的.complete属性的图像对象,你可以使用它,如果你已经设置了.src ,然后将任何事件监听器附加到它上面:

 var img=document.getElementById('myimg'); var func=function(){ // do your code here // `this` refers to the img object }; if(img.complete){ func.call(img); } else{ img.onload=func; } 

参考: http : //www.w3schools.com/jsref/prop_img_complete.asp

我会给需要这个约束的图像一个像mustLoad这样的类,其中:

  

然后创建一个通用的图像加载处理函数,例如:

 $('img.mustLoad').on('load',function(){ /* Fire your image resize code here */ }); 

编辑

为了回应你关于弃用.load()评论,不推荐使用.load() ,而选择.on('load') 来减少 onLoad事件和Ajax加载之间的歧义 。

在等待加载多个图像的情况下:

 var images = $("#div-with-images img"); var loadedImgNum = 0; images.on('load', function(){ loadedImgNum += 1; if (loadedImgNum == images.length) { // here all images loaded, do your stuff } }); 

我需要做的是在加载图像后启动图像resizefunction。

你确定需要加载图像吗? 在调整图像大小之前等待加载图像会导致页面布局出现大幅跳跃,尤其是在图像具有较大文件大小的情况下,例如动画GIF。

通常,对于图像resize,您只需要知道图像的内在尺寸。 虽然没有事件告诉你这个,但是很容易轮询图像以获取数据。 这样的事情可能特别有效:

  
 (function() { var images, l, i, tmp; if( document.querySelectorAll) { images = [].slice.call(document.querySelectorAll("img[data-resizeme]"),0); } else { tmp = document.getElementsByTagName("img"); images = []; // browser compatibility is fun! for( i=tmp.length-1; i>=0; i--) { if( tmp[i].getAttribute("data-resizeme")) images.unshift(tmp[i]); } } for( i=images.length-1; i>=0; i--) { images[i].onload = resizeImage; images[i].onerror = cancelImageResize; } var timer = setInterval(function() { for( i=images.length-1; i>=0; i--) { if( images[i].width) { resizeImage.call(images[i]); images[i].onload = null; cancelImageResize.call(images[i]); } } if( images.length == 0) clearInterval(timer); },100); // adjust granularity as needed - lower number is more responsive. function cancelImageResize() { var i; for( i=images.length-1; i>=0; i--) { if( images[i] == this) { images.splice(i,1); break; } } } function resizeImage() { console.log("Image "+this.src+" is "+this.width+"x"+this.height); } })(); 

希望这可以帮助!