Tuesday, October 18, 2011

How to use multiple onloads with external scripts ?

Hi All,

First of all thanks for visiting my blog. I recently working on oracle portlets and i had to add multiple portlets on my single page, that created conflict since both portlets had onload events and that created multiple onload events.

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

addOnloadEvent(myFunctionName);

// Or to pass arguments

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

Cheers,

Ujjwal Soni