Handle multiple window.onload functions in Javascript

If you have more than one window.onload functions, how do you handle it? One easiest way to do that is include all functions in  window.onload e.g,

window.onload=function(){

function1;

function2;

function3;

}

where function1, function2 and function3 are the functions which are needed during onload event.  This is fine when you are the only designer of your page. But if a page is designed by several designers and if several external javascript files are invloved with it then it is not so easier. To overcome the issue, I have found few articles over net and discussed here,

Solution1: Having an array filled with onload events and then call those events one by one (using for loop) in window.onlaod function.

Here is the link of  solution 1: http://www.netlobo.com/wom.html

Solution 2: Checking whether it has an onload event, if exist then load that with the new one otherwise consider the event as a fresh onload event.

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

Solution 3: It is similar to solution 2 but less code size,

function addLoadEvent(func) {  
   var oldonload = window.onload;  
   if (typeof window.onload != ‘function’) {  
     window.onload = func;  
   } else {  
     window.onload = function() {  
       if (oldonload) {  
         oldonload();  
       }  
       func();  
     }  
   }  
}

If you know more better approach, why dont you share with us.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s