0

When should I use window.onload and when should I use window.addEventListener("load", someFunction()) ?

1 Answers1

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