728x90
How to use multiple window.onload events with external scripts
faq216-4862
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?

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);

// Or to pass arguments

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

'Developer > JavaScript' 카테고리의 다른 글

이메일 주소 검증  (0) 2007.05.02
javascript cookie  (0) 2007.05.02
문자열이 ASCII 코드로만 이루어졌는지 체크하는 함수  (0) 2007.04.26

+ Recent posts