Rahul Iyer
Rahul Iyer

Reputation: 21025

What happens if multiple scripts set window.onload?

There are a number of posts on StackOverflow and other websites regarding the problem of avoiding namespace collisions. In my scenario, I just want a method in my JavaScript to be executed after the DOM is accessible.

If I do the following will it avoid namespace collisions?

<script type="text/javascript">window.onload = function() { //Define my namespace var here, and execute all my code }</script>

What if a script that is injected later also sets an onload function ? Will mine get overwritten? I'm fully aware that I can test this out, but I would also like some feedback as I am new to JavaScript and there could be a number of other scenarios which will do the something that I am not aware of.

EDIT: I need to support only Safari 5.0+

Upvotes: 1

Views: 1448

Answers (4)

LogPi
LogPi

Reputation: 706

It'll be overriden . In Javascript, when you define handle event like

window.onload = function(){
   console.log("in Load function 1");

};
window.onload = function(){
  console.log(" In load function 2");
};

That will make an " assign " window.onload => function() . And window.onload will be assign to last function .

But in jQuery, You can handle event in many times and the browser will make all

$("body").on("click",function(){
console.log("make a callback function 1");
});
$("body").on("click",function(){
console.log("make a callback function 2");
});

Because jQuery make a callback not "assign". Hope it helps you.

Upvotes: 0

Amnon
Amnon

Reputation: 2888

There's lots of information on this, but here's the short version:

if you want to play nicely with onload, you can do

var prev_onLoad = window.onload;
window.onload = function() {
    if (typeof(prev_onLoad)=='function')
        prev_onLoad();

    // rest of your onLoad handler goes here
}

and hope that other's play nicely or make sure that's the last setting of onload in the code.

However, more modern browsers have event registration functions (addEventListener and attachEvent on IE) which take care of this chaining among other things. Quite a few cross-browser onload event functions have been written which take care of this logic for you.

Upvotes: 1

CodeHacker
CodeHacker

Reputation: 2138

This is a fine Javascript way to do it right

function addLoadEvent(func) {
 var oldonload = window.onload;
 if (typeof window.onload != 'function') {
    window.onload = func;
 } else {
    window.onload = function() {
    if (oldonload) {
      oldonload();
    }
    func();
   }
 }
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
   /* more code to run on page load */
});

Explained Source

Upvotes: 1

Oriol
Oriol

Reputation: 288510

Yes, the last one will overwrite the previous ones.

The solution: use the new event API: addEventListener.

Upvotes: 3

Related Questions