Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use multiple window.onload events with external scripts

Javascript Events

How to use multiple window.onload events with external scripts

by  adam0101  Posted    (Edited  )
Scripts probably conflict most often when using the onLoad event. Have you ever used code like this?

window.onload=myInitFunction;

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.
Code:
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[fnc]();
      };
    }
    else 
      window.onload = fnc;
  }
}

Example:
Code:
addOnloadEvent(myFunctionName);

[green]// Or to pass arguments[/green]

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

Adam
http://adameslinger.blogspot.com//
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top