10

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?
0

3 Answers 3

18
  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.

Sign up to request clarification or add additional context in comments.

1 Comment

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: jsfiddle.net/ag4snbpz - So please, avoid using pure onload, onclick etc. methods!
9

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.

1 Comment

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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.