JS DOM: Load JS in HTML (defer, async, module)
Load Order Diagram
Stop the World Loading
When a JavaScript appears in a HTML page:
<script src="some.js"></script>
or
<script>/* code */</script>
the browser fetch and execute the script right away, and wait for it to finish, before loading any HTML that appear after the script tag.
This means:
- If your JavaScript manipulate the page's HTML elements that's below the script, it'll fail because those element are not loaded yet.
- If your JavaScript is slow, user will see the browser freeze, showing no content after the script, until the script execution is finished.
in year 2000s, people always place the script tag at the bottom of the page, right before the </body> tag.
Deferred Load
You can use the attribute defer like this:
<script defer src="file.js"></script>
defer means run script after the page finished parsing.
The execution order of multiple defer script tags, is the order they appear on HTML page.
π WARNING:
There is no =true or =false after async or defer.
π WARNING:
When using defer or async, you must have a src=val. You cannot use it like this:
<script defer>code</script>.
That'll behave the same as without defer/async.
As of 2013-07-11, all major browser support defer.
Async Load
async (asynchronous) means run the script and continue loading the HTML page at the same time.
<script async src="file.js"></script>
π WARNING:
with async, your script will not see HTML elements that are below the script tag, because they are not loaded yet.
If both async and defer are specified, it behaves as if only defer is specified.
The execution order of multiple async scripts is not specified. (not guaranteed to be in the order on the page.)
As of 2013-07-11, all major browser support async.
Module Script Load Order
if the script tag has attribute
type="module",
it defaults to
defer
loading unless
async
is specified.