search

Home  >  Q&A  >  body text

javascript - All js files introduced by the page, each js file has window.onload. Occasionally, a certain js file is not executed.

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? ?

習慣沉默習慣沉默2718 days ago906

reply all(5)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-26 10:57:06

    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);} 

    reply
    0
  • 黄舟

    黄舟2017-06-26 10:57:06

    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();
                }
            }
        }

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-26 10:57:06

    • 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.

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-26 10:57:06

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

    reply
    0
  • 代言

    代言2017-06-26 10:57:06

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

    reply
    0
  • Cancelreply