jQuery或Javascript检查图像是否已加载 [英] jQuery or Javascript check if image loaded
问题描述
我知道Stackoverflow上有很多这些,但我没有找到一个适用于我最近版本的jquery(1.10.2)。
I know there is a lot of these on Stackoverflow but I haven't found one that works for me in a recent version of jquery (1.10.2).
我确实尝试过:
$(。lazy)。load(function(){}
但是我相信经过一些研究使用 .load
来检测图像加载在jQuery 1.8中已被弃用。我需要做什么加载图像后会激活一个图像大小调整功能。我无法控制
HTML,目前我不得不通过附加属性通过jQuery添加图像尺寸(通过 .attr()
)一旦页面加载,我就可以使用lazyload js。
But I believe after some research using .load
to detect image load is deprecated in jQuery 1.8. What I need to do is fire an image resize function once the images are loaded. I don't have control over the
HTML and at the moment I am having to add the image dimensions via jQuery by attaching an attribute (via .attr()
) once page loads so that I can use lazyload js.
问题是我需要一个准确的方法来保存关闭所有各种脚本,直到图像正确加载,否则函数有时会在每个图像加载之前触发。我尝试使用 $(window).load(function(){});
但是有时它仍会在每个图像加载之前触发。
The problem is that I need an accurate way to hold off all my various scripts until the image has loaded properly else the functions sometimes fire before every image had loaded. I have tried using $(window).load(function (){});
however it sometimes still fires before every image had loaded.
推荐答案
我通常这样做:
var image = new Image();
image.onload = function () {
console.info("Image loaded !");
//do something...
}
image.onerror = function () {
console.error("Cannot load image");
//do something else...
}
image.src = "/images/blah/foo.jpg";
请记住加载是异步的,所以你必须继续 onload 和 onerror 事件。
Remember that the loading is asynchronous so you have to continue the script inside the onload and onerror events.
这篇关于jQuery或Javascript检查图像是否已加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!