开发者

Javascript Image Object - Handle onload Event

I'm trying to preload image on click event:

// new 开发者_如何学Pythonimage 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?


.complete is a property of the image object, not an event that you can attach to. Use the onload event:

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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜