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