Alan Edwardes

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

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.

5 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 ;)

Add a Comment

29th of March 2010 at 2:02 PM

2 years, 1 month ago

written by Alan Edwardes.

195 words

5 comments so far

feed for comments on this post

rand: Creating a Super "heavy" Bus ...

next: Running Theme Hospital on Windows ...

prev: Hello NearlyFreeSpeech.NET

share:FacebookTwitterRedditdiggStumbleUpondeliciousHacker NewsLinkedIn

add a comment

© 2006 – 2012 Alan Edwardes / code on github
Top