6

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?

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

4 Comments

well - I can't really, it has to be on click - and it opens the url taken from the href attribute of the <a> tag - unless I obviously misunderstood your suggestion.
Why is it important to call it before the src property is set?
Thanks James - it seem to be working now. I'm just wondering why the .complete call didn't work.
@user398341, .complete is a property stating whether the image has been loaded, not an event that you can attach to. Your if statement was run immediately after setting the image src - it probably would never be true at that point (unless it was cached maybe?). I've updated the answer a little to make that a bit more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.