Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Image Object - Handle onload Event

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?

like image 314
user398341 Avatar asked Sep 28 '11 19:09

user398341


People also ask

What is IMG onload?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Is there an onload function in JavaScript?

In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.


1 Answers

.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)

like image 153
James Hill Avatar answered Oct 17 '22 13:10

James Hill