What happens if multiple scripts set window.onload?

一笑奈何 提交于 2019-12-02 08:39:42

问题


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+


回答1:


Yes, the last one will overwrite the previous ones.

The solution: use the new event API: addEventListener.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/21298282/what-happens-if-multiple-scripts-set-window-onload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!