Thursday, June 11, 2009

JavaScript window event load order


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(){
window.onload = function(){
function sayOne(){
function sayTwo(){
function sayThree(){
if(window.attachEvent){//specifically for IE and Opera
else if(window.addEventListener){//all others
< /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?