Yesterday I was again confronted with Explorer ignoring my img.onload event in Javascript. The image would load fine, but the event would not fire. In the end it turned out I was initializing my onload after setting the src.
Now this should be a perfectly safe practice. Javascript is single threaded, which means that it will only run one piece of code at a time. And only when the code returns control to Javascripts, events are able to fire.
It seems IE has a different take on this. In certain occasions, it seems especially when the image is cached, the following alert will never fire:
var img = new Image;
img.src = "hello.jpg";
img.onload = function(){
alert("onload fired");
}
The simple fix and therefore best practice on this matter is to set the onload callback first and the src after that.
var img = new Image;
img.onload = function(){
alert("onload fired");
}
img.src = "hello.jpg";
Now the callback cannot possibly be skipped if the image onload event fires prematurely :)
It does feel a little counter intuitive though. Why does it feel more natural to first set the src and then set the onload... Ahwell, if IE is any concern to you, try to withstand that urge :)
Hope it helps you!