Thursday, June 11, 2009

JavaScript window event load order

Hi.

Here's an observation I ran across when wondering about the order of event execution when registering events on a page. Let's take a look at the following code first:

< script type="text/javascript" >
/*window.onload = function(){
sayOne();
};
window.onload = function(){
sayTwo();
};*/
function sayOne(){
alert(1);
}
function sayTwo(){
alert(2);
}
function sayThree(){
alert(3);
}
if(window.attachEvent){//specifically for IE and Opera
window.attachEvent("onload",sayOne);
window.attachEvent("onload",sayTwo);
window.attachEvent("onload",sayThree);
}
else if(window.addEventListener){//all others
window.addEventListener("load",sayOne,false);
window.addEventListener("load",sayTwo,false);
window.addEventListener("load",sayThree,false);
}
< /script>

If only the two commented lines at the top are uncommented (the ones using window.onload), then the "onload" event registered to "sayOne" gets overwritten by the second event handler registration to "sayTwo". Thus, only the "sayTwo" function gets executed, while the "sayOne" function will never be called.

Now, using the W3C and Microsoft event registration mechanisms, all the registered event handlers are invoked, but their orders differ in the two primary browsers viz. Internet Explorer(IE) and Firefox (FF). In IE, they seem to get pushed onto some sort of stack and the event handlers are invoked in the reverse order of them being "attached" to the window. Thus, in IE, the order of function calls on the window being loaded is:
  • sayThree
  • sayTwo
  • sayOne

However, in FF and all other browsers (tested this code in FF 3.0.11, IE7 & 8, Opera 9.64, Safari 4 (Public Beta) and Chrome 2.0.172), the functions are called in the order in which they are registered (as in a queue). All the browsers followed the expected event order execution except IE (no surprises there)!!! Also interesting is that Opera implements both "attachEVent" and "addEventListener".

I guess this quirk is just a browser implementation decision by the companies, but I wonder what the W3C has to say about it?

Cheers.