Handling Multiple JavaScript Inits
If you want to run some JavaScript every time a window is loaded or refreshed, a typical handler idiom used is:
1 2 3 4 5 6 7 | window.onload = function() { // do something doSomthing(); // do a second thing doSomethingElse(); } |
That’s all fine and dandy, assuming that you know that you want to run only a set number of functions for each page.
However, say if the above code is to be run for every page on a site, but a couple of other pages are going to use an additional handler as well. If you simply replicate the above code, only the last occurrence of the handler will run at window load/refresh. This is because the last installed handler overrides all earlier installed handlers.
To get around this, in the second (and subsequent) assignments to window.onload, the trick is to save the old handler, and then call the saved handler before your new handler. It’s simpler to demonstrate:
1 2 3 4 5 6 7 8 9 10 11 12 | var old = window.onload; if (typeof old == 'function') { window.onload = function() { // do original onload old(); // do the new thing doYetMore(); } } else { window.onload = doYetMore; } |
Pretty cool, eh?
Leave a Reply