TIL using defer/async
POSTED ON:
TAGS: optimization javascript mdn
So an old and often-touted best practice for performance has been to load your JavaScript in the footer of the document to avoid render blocking of scripts. By putting it in the footer, the DOM is constructed before your scripts have a chance to run.
With the advent of JS applications being the full site, however, it has been more commonplace in certain architectures to place <script>
elements in the document <head>
.
Instead, you're better off just using JS resource hints like async
or defer
.
async
anddefer
both load JavaScript asynchronously without render blocking, but async executes as soon as possible while defer runs in sequence toward the end of the loading process, just before theDOMContentLoaded
event.
For async:
Once the resource is gathered from the internet, it fires. That's useful for libraries/frameworks that your code is piggybacking off of. Or JS that needs to load, like configuration files.
What about defer:
It's useful for when you need to finally start your Javascript.
Now that the JS framework started, activate your code.
And what is DOMContentLoaded? It's when HTML is ready.
The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts (
<script defer src="…">
and<script type="module">
) have downloaded and executed. It doesn't wait for other things like images, subframes, and async scripts to finish loading.
via MDN - Window: DOMContentLoaded event
via What's The Difference Between Async & Defer?
Related TILs
Tagged: optimization