How To Add Functions To Javascript onload Over Third Party Scripts; Playing Nice
By Angsuman Chakraborty, Gaea News NetworkWednesday, February 7, 2007
As a javascript developer using onload often you will find that other script authors too love to use onload. Unfortunately onload accepts a function name and your reassigning will prevent others from using onload. Here is a script which allows you to use onload even when others have used it and without breaking their script.
The key idea is that you should be able to stack your function(s) above / below existing function call. Let’s look at the sample code below:
<script language="javascript">
// Third party script using onload to do its stuff after the page has loaded
window.onload = oldOnload;
function oldOnload() {
alert('oldOnload');
}
</script>
<script language="javascript">
var nowOnload = window.onload; // Let's save the existing assignment, if any
window.onload = function () {
// Here is your precious function
// You can call as many functions as you want here;
myOnloadFunction1();
/...
// Now we call old function which was assigned to onLoad, thus playing nice
if(nowOnload != null && typeof(nowOnload) == 'function') {
nowOnload();
}
}
// Your precious function
function myOnloadFunction1() {
alert('myOnloadFunction1');
}
</script>
I think I have well commented the code to make the script self-explanatory, but feel to ask questions. The code has been tested on Firefox, Internet Explorer and Opera.
March 2, 2010: 4:40 pm
I find it humorous the SEO has optimized this site as the first hit in my search yet the site is so feeble as to not even show the ‘content’ code that it indexed. |
Ryan |
October 23, 2008: 3:44 pm
For those who STILL can’t see the code, here it is… you can also view source on this page and find it. All I did was replace the ASCII HTML characters.
var nowOnload = window.onload; // Let's save the existing assignment, if any // Now we call old function which was assigned to onLoad, thus playing nice // Your precious function |
October 26, 2007: 6:30 am
Great idea. I created a function, addEventHandler, that simplifies adding this technique to new Javascripts. Thanks for addressing this issue. It was a recent concern of mine. |
February 8, 2007: 1:08 am
hi there, I don’t see any code — I use firefox 1.5.x on windows. Thank you, BR, |
Ken |
zartan