How to use multiple window.onload events with external scripts
Posted: 19 Feb 04 (Edited 20 Sep 05)

Scripts probably conflict most often when using the onLoad event. Have you ever used code like this?


This is fine if you're sure myInitFunction() will be the only function that needs to be called when the page is loaded. But how can you know for sure? What if a page that calls your script has code in its <BODY onload="..."> ? What if there's another external script on the page that also assigns a function to the onload event? The code above will overwrite what was there with your code and that's not good.

Use the function below to add your function without replacing what is already in the onLoad.


function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
      window.onload = fnc;




// Or to pass arguments

addOnloadEvent(function(){ myFunctionName('myArgument') });

+ Recent posts