Script Loading, Async, Defer and Modules

Intermediate · 10 min

How a plain script blocks the parser, what async, defer and type=module change about download and execution order, and which to choose for each kind of script.

Before thisLink Elements, Stylesheets and Icons

Web Dev Simplified · 10 min

Script Loading, Async, Defer and Modules

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A plain `<script src>` stops the HTML parser while it downloads and runs. A slow script in the head delays everything below it.
  • `defer` downloads in parallel and runs after parsing, in document order, before `DOMContentLoaded`. In a test, a slow deferred script that came first still ran before a fast one that came second.
  • `async` downloads in parallel and runs as soon as it arrives, in any order, so it suits independent scripts such as analytics. Where it ran relative to `DOMContentLoaded` varied between browsers in a test.
  • `type="module"` scripts are deferred by default, run in order, in strict mode, with `document.currentScript` null. The same module URL included twice ran once.
  • `defer` does nothing on an inline script. In a test, an inline script with `defer` ran immediately, in place.

Why scripts block

When the parser meets a <script>, it cannot carry on reading HTML. The script might call document.write, change the DOM it is building or ask about layout. So the parser stops, fetches the file if it has a src, runs it, and only then continues. That is what a classic script does, and it is why putting scripts at the end of <body> was the standard advice for a decade: content first, scripts last.

A script in the head with a slow server is a blank page for as long as the download takes. The async, defer and type="module" attributes exist to remove that wait while keeping control of when the code runs. Rendering fundamentals are in how browsers render a page.

What I observed

I loaded one page, served from a local server with controlled delays, containing: a classic script delayed 300ms, a defer script delayed 400ms followed by a fast defer script, an async script delayed 700ms and a fast async one, an external module, an inline module, an inline script with defer, and a plain inline script in the body. Each pushed its name into a log. The order was:

inline-head, sync-slow, inline-with-defer-attr, body-inline,
async-fast, defer-slow, defer-fast, mod-a, inline-module,
DOMContentLoaded, async-slow, load

That is Chromium and Firefox. WebKit matched except async-fast ran after DOMContentLoaded, just before async-slow.

Reading the result

Classic scripts run in place. sync-slow ran before anything after it, the parser having waited for it.

defer waits, then runs in order. defer-slow (400ms) ran before defer-fast, even though the fast one finished downloading first, and both ran before DOMContentLoaded. That order guarantee is why defer is the right default for scripts that depend on the DOM or on each other. The deferred scripts download in parallel with parsing, so nothing blocked.

async runs when ready. async-fast ran as soon as it arrived, ahead of the deferred scripts in two browsers and later in WebKit; async-slow landed after DOMContentLoaded, before load. The lesson is that nothing about async order is guaranteed. Use it only for scripts that do not care what else has run, such as analytics.

Modules defer by default. mod-a and inline-module ran after the deferred scripts, in document order, before DOMContentLoaded, with document.currentScript null. The same module URL written twice ran once. Modules also run in strict mode and can import, which is the subject of the JavaScript modules lesson. type="module" has been in Chrome since 61, Firefox 60 and Safari 10.1 according to compatibility data (BCD 8.1.10). Add async to a module to make it run as soon as it and its imports arrive.

defer on inline scripts is ignored. inline-with-defer-attr ran immediately, before body-inline. If you need an inline script to wait for the DOM, make it a module or use a DOMContentLoaded listener.

Modules and file URLs

A small surprise: modules are fetched under CORS rules. Opening a page with a module from disk, as a file:// URL, failed in Chromium (a CORS error in the console) while Firefox ran it. Use a local dev server; it is also what you will have in production.

Choosing

  • Your own app code, depends on the DOM: defer, or type="module".
  • Independent third-party code: async.
  • A tiny script that must run before first paint, such as one that sets a theme class to avoid a flash: inline and plain, as small as possible.
  • Nothing else: avoid plain scripts in the head.

Scripts are not the only thing that blocks. A stylesheet before a script makes the script wait, as link elements showed. Heavy scripts also cost time after they load; that is a performance topic. For loading a module on demand, see dynamic import.

What the video covers

The embed is the whole of Web Dev Simplified’s “What Is The Fastest Way To Load JavaScript” (November 2018). Its description says it compares the three ways to load JavaScript, normal, async and defer script tags, how each affects page speed and their pros and cons. It is nearly eight years old and predates modules being the norm, so it does not cover type="module", which comes from the lesson and my test above. There are no chapters and I could not read a transcript. The runner-up is a 2018 video of tests of async and defer. My results were run in headless Chromium, Firefox and WebKit; the numbers are timing-dependent, so treat the async ordering as an example, not a rule.

Where this fits

This follows link elements. Next, resource hints cover telling the browser about resources early, including modulepreload.

Check yourself

  1. 01Two scripts, `a.js` (slow) then `b.js` (fast), both have `defer`. In what order do they run?

    `a.js` then `b.js`, always. Deferred scripts execute in document order once parsing is done, even if `b.js` arrives first. In a test with a 400ms and an instant script, the slow one ran first.

  2. 02When would you choose `async` over `defer`?

    When the script is independent of the page and other scripts, such as analytics or an ad tag, and you want it to run as soon as it arrives. `async` gives no ordering guarantee and may run before or after the document finishes parsing, so a script that needs the DOM or another script should use `defer`.

  3. 03You add `defer` to an inline `<script>` block. What happens?

    Nothing: `defer` only applies to scripts with a `src`. In a test, the inline script ran immediately where it appeared, before the body's own inline script. For an inline script that needs the DOM, use `type="module"` or wait for `DOMContentLoaded`.

  4. 04Why does a page with `<script type="module" src="main.js">` opened from a file on disk fail in Chrome?

    Module scripts are fetched with CORS rules, and `file://` pages have no origin that allows it. In a test, Chromium blocked the module from a local file while Firefox ran it. Serve the page over HTTP, even with a local dev server.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark