Using window.onload without overwriting existing onload event handlers

When you are creating reusable javascript files, there are times when you want to tap into the window.onload event, which is fired when the window has finished loading the content.

The problem here, is that you can’t have multiple event handlers for the same event.

So if you have a page that uses 2 scripts which both use the window.onload event, then which ever is loaded last will win, and the other script will never catch the event.

Well one way you can deal with this problem is to write your window.onload (or other events for that matter) using this type of a pattern:

    //-- see if there is already something on the onload
    var tempFunc = window.onload;
    //-- create our event handler
    window.onload = function(){
        //-- if tempFunc is a function, try to call it
        if (typeof (tempFunc) == "function"){
            try{
                tempFunc();
            } catch(e){} //--- if it errors, don't let it crash our script
        }
     //-- Call your onload function here
    }

This way, you can have several function that all utilize the onload event, and none of them have to know about each other.

 

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