What happens if multiple scripts set [removed]?

前端 未结 4 1105
灰色年华
灰色年华 2021-01-24 00:41

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

4条回答
  •  独厮守ぢ
    2021-01-24 01:29

    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.

提交回复
热议问题