brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: defer and async on a script tag behave differently, and order is the reason

Web-Development
~/tips/tip-script-defer-vs-async

cat ~/tips/tip-script-defer-vs-async.md

Pick defer for scripts that depend on each other and async for independent ones.

Both attributes stop a script from blocking the HTML parser while it downloads. What differs is when the script runs, and I think they are easy to mix up.

<script src="/js/vendor.js" defer></script>
<script src="/js/app.js" defer></script>
<script src="https://stats.example.com/s.js" async></script>
<script type="module" src="/js/main.js"></script>

A defer script downloads in parallel and runs after the document has been parsed, just before DOMContentLoaded. Deferred scripts run in the order they appear, so app.js can rely on vendor.js.

An async script runs as soon as it has downloaded, which can be before or after parsing finishes and in any order. That suits a stats script that depends on nothing and that nothing depends on.

Module scripts are deferred by default, so the last line needs no attribute. Adding async to a module makes it run as soon as it and its imports are ready.

The trap: both attributes only work for scripts with a src. On an inline classic script defer does nothing and the code runs immediately. If an inline snippet needs the DOM, wrap it in a DOMContentLoaded listener or move it into a file.

Further reading: MDN: The script element

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link