What happens if multiple scripts set [removed]?

前端 未结 4 1073
灰色年华
灰色年华 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:26

    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

提交回复
热议问题