JS DOM: Load JS in HTML (defer, async, module)

By Xah Lee. Date: . Last updated: .

Load Order Diagram

js async defer 6hhq9
JavaScript fetch and execute order γ€”image source whatwg.org , Β© https://creativecommons.org/licenses/by/4.0/legalcode 〕

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:

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.

Execution Order of Loading JS in HTML