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

Steven Ventimiglia
Steven Ventimiglia
27,371 Points

What's the difference between these two approaches...?

Surrounding the entire JS file in:

document.addEventListener('DOMContentLoaded', () => {
 ...
}

As opposed to simply adding async to the script tag:

<script async type="text/javascript" src="app.js"></script>

Adding async seems just as effective, and prevents us from throwing all of the code we've written into a "DOM gift box" for it to be delivered correctly.

1 Answer

Steven Parker
Steven Parker
229,744 Points

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Using it causes your script (which is already loaded) to start running, synchronously, as soon as the elements exist.

But using the async attribute allows parsing to continue while the script is being loaded. You don't know how much later it will start running. There's certainly a good chance that the page elements will exist by then, but there's no guarantee unless your script tag is placed at the end of the page content.

So the choice of technique would might be based on how critical the script is to page operation.