[Javascript] window.onload questions

Paul Novitski paul at novitskisoftware.com
Wed Dec 7 13:57:52 CST 2005


At 06:02 AM 12/6/2005, Schalk wrote:
>I have two seperate .js file that I load into a html page. Both of 
>them load their init() function with the window.onload function. 
> From what I can see it seems that the second script is overriding 
>the first script and the first one is never run and therefore does 
>not function.
>
>First, can I call the onload functions of both in the second script, 
>even though they are in seperate files? If not, is it best then to 
>merge the two into one file or do I have another option? Thanks for 
>all of your input.

Hi Shalk,

Here's a bit of script I include with each function that I want to 
run on pageload:
___________________________

// here's the onload manager:

var loadDoSomething = window.onload;

window.onload = function()
{
                 if (loadDoSomething) loadDoSomething();
         doSomething();
}


...


// here's the function I want to run:

function doSomething()
{
         ...
}
___________________________

where "doSomething" is the name of the function you want to run and 
"loadDoSomething" is a variable name that's unique for each loaded function.

As you can see, this is a close cousin to the script by Simon 
Willison.  The advantage of his script is that, once the master 
script is loaded, you use a one-line function call to add more 
functions to the onload chain.  The disadvantage of his script is 
that you need to manually manage the organization of linked scripts, 
ensuring that the master script is loaded once & only once in order 
for the system to work.

The advantage of my method is that each linked script handles its own 
addition to the onload chain itself, not requiring a master 
script.  The disadvantage is that you need to change the name of the 
load variable ("loadDoSomething" in my example above) to something 
unique for each instance.

I prefer my method only because I want the scripts I link in to be 
self-managing.  The whole reason I went in this direction in the 
first place was so I wouldn't have to babysit scripts, worrying about 
which ones were loaded and in what order.

Regards,
Paul  




More information about the Javascript mailing list