javascript - All js files introduced by the page, each js file has window.onload. Occasionally, a certain js file is not executed.
習慣沉默
習慣沉默 2017-06-26 10:55:06
0
5
901

1. Introduce a.js and b.js in page A; there is no problem with both a.js and b.js using window.onload;
But I also introduce a.js and c in page B. js, occasionally a.js is as if it is not executed at all
But I directly put the things in window.onload in a.js into the onload of c.js in page B, and it is executed correctly. I don’t know why. what happened? ?

習慣沉默
習慣沉默

reply all(5)
phpcn_u1582

window.onload is only used once, so there will be conflicts when multiple js use it at the same time.
Solution

1.用jQuery使用ready()方法替换onload
2.在window.onload中一次加载所有js文件,例:window.onload=function(){function(a);function(b);} 
黄舟

I tried it. The window can be bound multiple times, but it will only take effect the last time. You can compare my two examples below to understand your situation.

    //方式1:
    window.onload=function () {
        console.log("1");
    }
    window.onload=function () {
        console.log("2");
    }
//    输出2
//    -------------------------------分割线
//    方式2:
    function fn1() {
        console.log("1");
    }
    function fn2() {
        console.log("2");
    }
    addEventLoad(fn1);
    addEventLoad(fn2);
    //输出1  2
    function addEventLoad(fn){
        var oldFn = window.onload;
        if(typeof window.onload != 'function'){
            window.onload = fn;
        }else{
            window.onload = function(){
                oldFn();
                fn();
            }
        }
    }
大家讲道理
  • For events set through the window.onload = function() { ... } method, the later window.onload value will overwrite the previous one, so only the last one will take effect. (This is the same as calling a = 1; a = 2; a =3; )

  • If you need to bind the onload event of window multiple times, it is recommended to use addEventListener:

window.addEventListener('load', function() { ... }, false);
  • Note that attachEvent is used in the ID instead of addEventListener:

window.attachEvent('onload', function() { ... });
  • Also note that 'load' is used in addEventListener, while 'onload' is used in attachEvent.

世界只因有你

The window.onload() method can only be bound once. If you bind multiple times, only the last one will take effect

代言

window.onload will only call the last one, and the previous ones will be overwritten.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template