Managing multiple onLoad events in JavaScript

Apr 25

It is possible to add multiple function calls within the standard onload event within the body tag, however there comes a time when we may want to use the window.onload call within our webpages. This will clash with our onload calls already defined within the body tag.

This article written by Robert Dominy, demonstrates the use of a separate script that adds each function to an array which will subsequently execute each onload function in turn. Without it we have no way to guarantee that all our required functions are called.

JavaScript Source

Copy the following and paste into the HEAD section of your page.

  1. <script language="JavaScript">
  2. // Browser Detection
  3. isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
  4. NS4 = (document.layers) ? true : false;
  5. IEmac = ((document.all)&&(isMac)) ? true : false;
  6. IE4plus = (document.all) ? true : false;
  7. IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
  8. IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
  9. ver4 = (NS4 || IE4plus) ? true : false;
  10. NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
  11. // Body onload utility (supports multiple onload functions)
  12. var gSafeOnload = new Array();
  13. function SafeAddOnload(f)
  14. {
  15. if (IEmac && IE4) // IE 4.5 blows out on testing window.onload
  16. {
  17. window.onload = SafeOnload;
  18. gSafeOnload[gSafeOnload.length] = f;
  19. }
  20. else if (window.onload)
  21. {
  22. if (window.onload != SafeOnload)
  23. {
  24. gSafeOnload[0] = window.onload;
  25. window.onload = SafeOnload;
  26. }
  27. gSafeOnload[gSafeOnload.length] = f;
  28. }
  29. else
  30. window.onload = f;
  31. }
  32. function SafeOnload()
  33. {
  34. for (var i=0;i<gSafeOnload.length;i++)
  35. gSafeOnload[i]();
  36. }
  37. // Call the following with your function as the argument
  38. SafeAddOnload(yourfunctioname);
  39. </script>

Filed under:
Scripting
Posted by:
James Griffin
Dated:
April 25, 2003