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? ?
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);}
黄舟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();
}
}
}
大家讲道理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
.
世界只因有你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
代言2017-06-26 10:57:06
window.onload will only call the last one, and the previous ones will be overwritten.