Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should making two calls to window.onload be valid?

Tags:

javascript

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.

like image 306
ubiquibacon Avatar asked Mar 14 '11 21:03

ubiquibacon


2 Answers

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);
like image 189
Nik Kalyani Avatar answered Sep 23 '22 19:09

Nik Kalyani


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>
like image 21
Darin Dimitrov Avatar answered Sep 22 '22 19:09

Darin Dimitrov