RSS

Load listeners

Thu, Jul 24, 2008

Code, JavaScript

Sometimes multiple scripts tied to the page’s OnLoad even do not work. This is because the scripts are most likely trying to assign event handlers for the same event. The fix is to call the functions from a single load handler.

window.onload = function()
{
   functionA();
   functionB();
}

A better approach however would be to be able to dynamically assign functions to the page’s load event by merely passing the following function a function’s name.

function addLoadListener(fn)
{
   if (typeof window.addEventListener != 'undefined')
   {window.addEventListener('load', fn, false);}

   else if (typeof document.addEventListener != 'undefined')
   {document.addEventListener('load', fn, false);}

   else if (typeof window.attachEvent != 'undefined')
   {window.attachEvent('onload', fn);}

   else
   {
        var oldfn = window.onload;

        if (typeof window.onload != 'function')
        {
            window.onload = fn;
        }
        else
        {
             window.onload = function()
             {
                  oldfn();
                  fn();
             };
         }
    }
}

To add an event we would now use:

addLoadListener(firstfunction);
addLoadListener(secondfunction);
addLoadListener(thirdfunction);

So why so do we test for so many different types of functions? Ah you know, BROWSERS. We are actually testing that these types are supported so that we can add our onload functions.

The W3C standard method is called addEventListener:

window.addEventListener('load', firstfunction, false);

The IE method is called attachEvent:

window.attachEvent('onload', firstfunction);
Share and Enjoy:
  • Facebook
  • Twitter
  • MySpace
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
,

Comments are closed.