Steven Ventimiglia
Steven Ventimiglia
22,422 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
130,895 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.