-1

I have a question concerning the difference between:

 1. <body onload="myFunction()">
 2. window.onload = myFunction;
 3. window.addEventListner("load", myFunction)
 4. window.onload = myFunction();

So are they all equivalent? and which one is the best practice to use?

alig
  • 15
  • 4
  • 1
    Does this answer your question? [window.onload vs

    ](https://stackoverflow.com/questions/191157/window-onload-vs-body-onload) and [attachEvent / addEventListener to Window onload / load - preferred way](https://stackoverflow.com/questions/5436521/attachevent-addeventlistener-to-window-onload-load-preferred-way). See also [How to make JavaScript execute after page load?](https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load)

    – Inigo Dec 07 '21 at 23:24
  • window.addEventListener is the preferred way to add events. – epascarello Dec 07 '21 at 23:39
  • The best one to use is ` – Sebastian Simon Dec 08 '21 at 01:06

1 Answers1

0

Yes, they are all equivalent. It is the same "load" event. I prefer to use DOMContentLoaded. That's what I check for before manipulating the DOM.

https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

DJones
  • 75
  • 3