I have two js files, each of which has its own window.onload handler. Depending on how I attach the two load handlers to the window object, I get a different behavior in the second handler.
In particular, here is my html file:
<html> <head> <title>Welcome to our site</title> <script type="text/javascript" src="script1.js"> </script> <script type="text/javascript" src="script2.js"> </script> </head> <body id="pageBody"> <h2 align="center"> <a href="http://www.whatever.com" id="redirect"> Wellcome to our site... c'mon in! </a> </h2> </body> </html>
It loads two js files, script1.js and script2.js.
Here is a version of these two scripts that leads to unexpected behavior (at least to me).
Script1.js:
window.onload = initAll1(); // attach first onload handler function initAll1() { alert("initAll1"); document.getElementById("redirect").onclick = foo; // attach an onclick handler } function foo() { alert("we are in foo"); return false; }
Script2.js:
addOnloadHandler(initAll2); // with this we should attach a second onload handler function initAll2() { alert("initAll2"); if (linkHasOnclickHandler(document.getElementById("redirect"))) { alert("correct!"); } else { alert("wrong!"); } } function addOnloadHandler (newFunction) { var oldevent = window.onload; if (typeof oldevent == "function") { window.onload = function() { if (oldevent) { oldevent(); } newFunction(); }; } else { window.onload = newFunction; } } function linkHasOnclickHandler() { var oldevent = document.getElementById("redirect").onclick; if (typeof oldevent == "function") { return true; } else { return false; } }
In Script2.js, I tried to add a second onload handler in a beautiful non-invasive way using the addOnloadHandler () function. This function makes no assumptions as to whether there is already a load handler attached to the window object. This is non-invasive because it must add a new handler without deleting the previous ones.
The fact is that when loading with addOnloadHandler (), initAll2 () is not able to detect the fact that document.getElementById ("redirect") already has foo () attached as an onclick event handler (see initAll1 ()), Warning message βwrong!β, which seems to me to be wrong behavior.
When I forget about addOnloadHandler () and attach both onload handlers in Script1.js using:
window.onload = function () {initAll1(); initAll2();};
then everything works as expected, and initAll2 () starts "correctly!". warning message.
Is there something wrong with addOnloadHandler ()? Can anyone make it work? I would really like to use it instead of the second method.
Thanks!