Alan Edwardes

Internet Explorer, Opera and JavaScript Image object "onload" Event

Old Content Warning

This post is very old (it was published 3 years ago), so I can't vouch for its content or accuracy. It may be here for posterity. Please take its content with a pinch of salt.

This is basically a post for the benefit of me and anyone else that is having trouble with Internet Explorer not executing the onload function when it's finished loading the image. This is a reiteration of this post on The Future of the Web.

The following code properly fires the onload function in all other browsers but internet explorer, which seems to only fire it the first time the image is actually downloaded - any versions of it pulled from the cache wont work - presumably because the image has finished loading before the onload event is attached to it.

var Img = new Image();
Img.src = '/images/image.png';
Img.onload = function(){
	alert('Loaded!');
}

So the way to fix this is to define the onload function before the source path:

var Img = new Image();
Img.onload = function(){
	alert('Loaded!');
}
Img.src = '/images/image.png';

Thus setting up the event before sending the browser off to get the image. This is a pretty un-obvious solution, but one that is not completely devoid of logic.

I've found this error to run right to IE9 beta, so it's clearly not going to be changed.

7 Comments

Nilesh Padariya's Gravatar
Nilesh Padariya
1

Thanks! your solution really works!!

Karsten Januszewski's Gravatar
2

Nice work around. Reported to IE team.

Alan Edwardes's Gravatar
3

Let me just reiterate, this isn't my solution; I reposted it (mainly for my benefit).

The original post is here (as stated in the first paragraph;) http://www.thefutureoftheweb.com/blog...

Sergiu Jurca's Gravatar
4

Funny software, this IE...it's literally upside down. Thanks!

SHiNAeS's Gravatar
5

Big Thanks!! It's work with my IE ;)

Ihrist Lord's Gravatar
6

Tnx! The simplest way to solve the problem.

Julien's Gravatar
7

Fantastic, works very well.

Add a Comment

29th of March 2010 at 2:02 PM

3 years, 1 month ago

I was 18 years old when I wrote this

195 words

7 comments so far

feed for comments on this post

rand: Erepublik Goes Stable

next: Running Theme Hospital on ...

prev: Hello NearlyFreeSpeech.NET

share:FacebookTwitterRedditdiggStumbleUpondeliciousHacker NewsLinkedIn

add a comment

© 2006 – 2013 Alan Edwardes / Source on GitHub
Top