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
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.
For events set through the
window.onload = function() { ... }
method, the laterwindow.onload
value will overwrite the previous one, so only the last one will take effect. (This is the same as callinga = 1; a = 2; a =3;
)If you need to bind the
onload
event ofwindow
multiple times, it is recommended to useaddEventListener
:Note that
attachEvent
is used in the ID instead ofaddEventListener
:Also note that
'load'
is used inaddEventListener
, while'onload'
is used inattachEvent
.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.