9

It seems to me that both events are fired when every resource and its dependent resources have finished loading. This rises some questions:

  1. Is there any difference between those events?
  2. Which event gets fired first?
  3. Which event could or should be preferred for adding an additional HTML element to the body after everything has been finished loading?
Chilly Code
  • 678
  • 2
  • 6
  • 17

3 Answers3

15
  1. As you say, they both do exactly the same thing. The advantage of addEventListener is that you can add more than one event listener to the load event.

  2. From some basic testing, it seems the listeners get called in the order they were set, though I don't know how reliable that is.

  3. You can use either method to do whatever you need.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14
  • No, they are handled different. The simple onload function can be overwritten, and it seems like it's executed first. The eventListeners get stacked, and all of them are executed. Spent like 3 hours debugging a script. It used a simple window.onload, which was later overwritten with another script, so the first script's onload never executed. Check this example: https://jsfiddle.net/ag4snbpz/ - So please, avoid using pure onload, onclick etc. methods! – David58 May 31 '23 at 17:31
5

They do NOT do exactly the same thing, at least in Firefox.

The reason is that window.onload is equivalent to window.addEventListener("load"), not document.addEventListener("load").

Although, all documentation I have seen says that they are equivalent.

Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
JPL
  • 111
  • 1
  • 4
  • 1
    What you are pointing out is valid, albeit common sense. In 99.9% of all situations, the document and window being fully loaded occurs at nearly the same time. – Abandoned Cart Feb 23 '20 at 16:59
0

1- From what I know adding an event listening gives you more freedom especially in removing the controls you added

2- Nothing I know about that. But I assume it shouldn't be a big difference

3- The EventListener allows you to control the element and remove the control at will and thus should be more useful

Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21