javascript 通过 jQuery 检测图像加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5292819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:40:32  来源:igfitidea点击:

Detect image load by jQuery

javascriptjqueryhtmlcssimage

提问by James

<img src="http://site.com/image.png" />

I change src of this image on .clickevent.

我在.click事件中更改了此图像的 src 。

There can be loaded more than 20 different images, after changing src.

更改后可以加载 20 多个不同的图像src

1) How do I know, was image already loaded (should be cached) or it has to be loaded?

1) 我怎么知道图像是已经加载(应该被缓存)还是必须被加载?

2) How to run two different functions, for loaded and not?

2)如何运行两个不同的函数,加载和不加载?

Thanks.

谢谢。

回答by jAndy

You need to attach an event handler for the load event:

您需要为 附加一个事件处理程序load event

Update 2017:

2017 年更新

$('img').on('load', function() {
    alert('new image loaded: ' + this.src);
});

Plain JS/DOM:

普通的 JS/DOM:

imgNode.onload = () => {
    alert('new image loaded: ' + this.src);
};