When should I use window.onload and when should I use window.addEventListener("load", someFunction()) ?
Asked
Active
Viewed 147 times
0
-
@EliasSoares not really, OP is not asking eventlistener vs onclick – Nidhin Joseph Jul 31 '19 at 23:04
-
@Nidhin Joseph it's the same answer for different events. – Elias Soares Aug 01 '19 at 01:09
1 Answers
0
You should always use window.addEventListener("load", someFunction)
as the event will not be overwritten.
Using window.onload
is subject to being overwritten by other code if you are using libraries who are not careful with your event listeners.
You can see that demonstrated below, where 3 is never displayed nor executed.
window.addEventListener("load", function(){ console.log(1); });
window.addEventListener("load", function(){ console.log(2); });
window.onload = function(){ console.log(3); };
window.onload = function(){ console.log(4); };
In general, the same principle will apply to using other types of event listeners such as input events (click, mouse, keyboard, etc).

Travis J
- 81,153
- 41
- 202
- 273