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.

 

Categories:  | 
Tuesday, December 05, 2006 3:33:52 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Name
E-mail
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

All content © 2008, Christopher May, Inc
Open Job Positions
On this page
Google Ads
This site
Calendar
<December 2008>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 1.9.6264.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: