Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Improving the Application Code The DOMContentLoaded Event

Couldn't you use "window.onload" instead?

Is there any downsides/upsides of using window.onload like

window.onload = function () {
  //code here
};

rather than doing

document.addEventListener('DOMContentLoaded', () => {
  //code here
});

? I feel like using "window.onload" is easier to type and uses less code to do the same thing.

1 Answer

Steven Parker
Steven Parker
231,271 Points

For trivial cases, it probably makes no difference; but for more complex or evolving projects:

  • the DOMContentLoaded event fires before associated resources load, the load event fires after
  • you can only have one "onload", but you can attach multiple listeners to an event
  • using addEventListener is considered a coding "best practice".

Oh, okay, thanks!