Event order in different browsers

I had an issue today where my event had to be triggered after another event in the onload property of body. I wasn’t sure if my event would be triggered after or before so I wrote a quick code to test it. I was pretty sure, from the very start, that the results would disappoint me.

Here’s the code I used to test.

<html>
<head>
 <title>Event Tests</title>
 <script>
 if(window.addEventListener){
 window.addEventListener('load',function(){alert('event1')},false);
 }else if(window.attachEvent){
 window.attachEvent('onload',function(){alert('event1');})
 }
 </script>
 <script src='jquery-min.js'></script>
 <script>
 $(document).ready(function(){
 alert('jq1');
 });

 if(window.addEventListener){
 window.addEventListener('load',function(){alert('event2')},false);
 }else if(window.attachEvent){
 window.attachEvent('onload',function(){alert('event2');})
 }

 $(document).ready(function(){
 alert('jq2');
 });
 </script>
</head>
<body onload='alert("event3")'>
 <script>
 if(window.addEventListener){
 window.addEventListener('load',function(){alert('event4')},false);
 }else if(window.attachEvent){
 window.attachEvent('onload',function(){alert('event4');})
 }
 $(document).ready(function(){
 alert('jq3');
 });
 if(window.addEventListener){
 window.addEventListener('load',function(){alert('event5')},false);
 }else if(window.attachEvent){
 window.attachEvent('onload',function(){alert('event5');})
 }
 </script>
 <h1>Event Tests</h1>
</body>
</html>

Firefox 3.5 & Google Chrome

Firefox and Chrome both worked as expected. The jQuery Events were triggered first as I suspected and I was starting to get happy. Here’s the order they executed.

  1. jq1
  2. jq2
  3. jq3
  4. event1
  5. event2
  6. event3
  7. event4
  8. event5

Internet Explorer 8

Here on the other hand things started to get ugly. My smile fade away while ie shouted the following:

  1. jq1
  2. jq2
  3. jq3
  4. event3
  5. event5
  6. event4
  7. event2
  8. event1

Internet Explorer 6 & 7

Run while you can.

  1. jq1
  2. jq2
  3. jq3
  4. event3
  5. event2
  6. event4
  7. event5
  8. event1

I think these results are completely nonsense. I’d be glad if someone could shed some light on this behavior. At least jQuery can save you from this madness.

Conclusion

Do you want to control the way your events trigger cross-browser without insane hacks? Go with jQuery.