Javascript 图像对象 - 处理 onload 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7588472/
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-26 00:37:18  来源:igfitidea点击:

Javascript Image Object - Handle onload Event

javascriptimagepreload

提问by user398341

I'm trying to preload image on click event:

我正在尝试在点击事件上预加载图像:

// new image object
var imgObject = new Image();

// assign the path to the image to the src property
imgObject.src = document.URL + 'image/image.jpg';

// check if image has loaded
if (imgObject.complete) {

But the complete call never returns true on the first click - any idea what I'm missing here?

但是,在第一次点击时,完整的调用永远不会返回 true - 知道我在这里遗漏了什么吗?

回答by James Hill

.completeis a property of the image object, not an event that you can attach to. Use the onloadevent:

.complete是图像对象的属性,而不是您可以附加到的事件。使用onload事件:

var image = new Image();
image.onload = function() {
    alert('image loaded');
};
image.src = document.URL + 'image/image.jpg';

Note:Be sure to attach to the onload hander before setting the source attribute.

注意:在设置 source 属性之前,一定要附加到 onload 处理程序。

Note Explanation: Image caching. If the image is cached then the onload event will fire immediately (sometimes before setting the handler)

注释说明:图像缓存。如果图像被缓存,则 onload 事件将立即触发(有时在设置处理程序之前)