Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between window.onload() and document.addEventListener('load', ..)? [duplicate]

Tags:

javascript

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?
like image 381
Chilly Code Avatar asked Jul 21 '16 09:07

Chilly Code


People also ask

What is the difference between window addEventListener and window onload?

Difference is that, window.onload event will only be called once, and it will override the previously attach onload event. While on the other hand, using window.addEventListener you can add as many functions as you want and they will all be called in parallel. For example, take the following code:

What is the use of window onload?

window.onload By default, it is fired when the entire page loads, including its content (images, css, scripts, etc.) In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.

What is the difference between document ready and window onload?

While the document ready is a jQuery event which means that it is only available in the jQuery library, the window.onload is a pure JavaScript event, and therefore, available in most browsers and libraries. The other main difference is apparent from their definitions.

What is onload and onload event?

onloads: The onloads event is fired when an object is fully loaded, there are two types of onload event one is windows onload and body onload. Windows onload: This window’s onload event fires at the start.


2 Answers

  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.

like image 157
Whothehellisthat Avatar answered Oct 16 '22 15:10

Whothehellisthat


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.

like image 24
JPL Avatar answered Oct 16 '22 15:10

JPL