Here's a way to use window.onload that won't break other scripts that also need to use it: Store the current value of window.onload before you set the new value, then call it as part of your own initialization.
I've written this short helper function to do the job for you:
function WindowOnload(f) {
var prev=window.onload;
window.onload=function(){ if(prev)prev(); f(); }
}
Here's an example of how to use it:
Replace this: | with this: |
---|---|
function my_init() {
. . .
}
window.onload = my_init;
|
function my_init() {
. . .
}
WindowOnload( my_init );
|
How does it work?
Each time you call WindowOnload() the current value of window.onload is stored in the local variable prev. It is then replaced by a function that calls prev() and then calls your initialisation function f(). Each call to WindowOnload() creates a new version of the prev local variable, so you get a chain of initialization functions that call each other in the correct order.
The first time WindowOnload() is called, window.onload may be null, so the init function checks that prev has a value before trying to call it as a function. This check is only really needed by Internet Explorer.
Why is this better?
This approach works correctly with all other scripts that want to use window.onload, no matter how they are written. There are initialization schemes that store init functions in an array, and then call them all in a loop, but they rely on all of the JavaScript on the page using the correct registration function. Just one script that doesn't play along will break everything else.
The WindowOnload() function works independently, but does not break other initialisation schemes.
(The ``WindowOnload()`` function is hereby assigned into the public domain.)