I have two blocks of JavaScript which both call functions via winodow.onload
. One of the functions is called on every page, but the other is only called on one specific page. On that page one function works, but the other does not, and I am not getting any errors that I can see.
Does it matter that both functions are called via window.onload
in different script blocks (see example)? Shouldn't this work?
<!--some html-->
<script language="JavaScript" type="text/javascript">
function firstFunction(){
//do stuff
}
window.onload = firstFunction;
</script>
<!--some html-->
<script language="JavaScript" type="text/javascript">
function secondFunction(){
//do stuff
}
window.onload = secondFunction;
</script>
<!--some html-->
UPDATE:
I ended up taking zzzzBov's suggestion of using jQuery's $(document).ready(doAction);
function. Now I have multiple.js
included on a single page all using this call and there is no conflict.
The recommended best practice for registering event handlers is to use "addEventListener" (see https://developer.mozilla.org/en/DOM/element.addEventListener). Using this method ensures that the handler is additive and does not replace existing handlers.
function something() {alert("1");}
function somethingElse() {alert("2");}
window.addEventListener("load", something, false);
window.addEventListener("load", somethingElse, false);
The second onload
assignment is erasing the first. So if you have two window.onload
assignments on the same page pointing to two different handlers the second will win. You will need to merge them into a single one:
<script type="text/javascript">
function firstFunction(){
//do stuff
}
</script>
<!--some html-->
<script type="text/javascript">
function secondFunction(){
//do stuff
}
</script>
<script type="text/javascript">
window.onload = function() {
firstFunction();
secondFunction();
};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With