[Javascript] Handle several window.onload functions
Paul Novitski
paul at novitskisoftware.com
Tue Jul 5 16:04:18 CDT 2005
At 01:22 PM 7/5/2005, Guillaume wrote:
>The problem i encounter is that i use several window.onload for the same
>document, wich cancel each other called separately. I'd like to build a
>global window.onload function, in wich i could add a list of different
>functions I fire up with window.onload.
Guillaume,
Welcome to the list!
Here's the multiple-onload method I've been using. I replicate the
following logic for each function I want to run on page load:
__________________
var oldLoader = window.onload;
window.onload = function()
{
if (oldLoader)
{
oldLoader();
}
jsDoSomething();
}
__________________
"oldLoader" is a variable name that you will change to be anything you
want. In fact, in order for this to work, every function you add to the
onload list must have a unique "oldLoader" variable name. (See the
two-function example below.)
The logic depends on the fact that window.onload() is a function which
begins null and acquires a non-null value when it's set to any
function. Here's the code logic:
1) Set a unique variable (e.g., "oldLoader") equal to window.onload. (Note
that if no other function has previously been set to run onload, oldLoader
will be null.)
2) Set window.onload equal to a function that examines oldLoader and runs
it if it's not null, then runs the function you want.
Here's an example with two functions to be run on page load:
__________________
var initLoader = window.onload;
window.onload = function() { if (initLoader) { initLoader(); }
jsInitialize();
}
...
var stylesLoader = window.onload;
window.onload = function() { if (stylesLoader) { stylesLoader(); }
jsMakeStyles();
}
__________________
When the first code is run, window.onload() is null, therefore initLoader
is null, therefore initLoader() is not set to run but jsInitialize is.
When the second code executes, window.onload() is not null, therefore
stylesLoader is not null, therefore stylesLoader() is executed [which
executes jsInitialize()] followed by jsMakeStyles().
When the page loads, the final execution sequence is:
- window.onload()
- stylesLoader()
- jsInitialize()
- jsMakeStyles()
It's a little bit to get your head around at first, but it seems to work
just fine.
Regards,
Paul
More information about the Javascript
mailing list