Javascript Image Object - Download Event

I am trying to preload an image in a 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 a full call never returns true on the first click - any idea that I'm missing here?

+5
source share
1 answer

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

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

Note. Be sure to connect to the onload loader before setting the source attribute.

Note. Explanation : image caching. If the image is cached, the onload event fires immediately (sometimes before installing the handler)

+10

All Articles