Script Loading Strategies

How to use async and defer attributes to optimize script loading and prevent render-blocking.

Internet6 min readConcept 32 of 35

What it is

Script Loading Strategies determine how the browser downloads and executes JavaScript files in relation to HTML parsing. There are three main approaches:

1. **Synchronous (Default)**: The browser stops HTML parsing, downloads the script, executes it, and then resumes parsing.

2. **Async**: The browser downloads the script in the background while parsing HTML. As soon as the download finishes, it pauses parsing to execute the script.

3. **Defer**: The browser downloads the script in the background while parsing HTML. It waits until HTML parsing is 100% complete before executing the script.

Why it matters

Optimizing script loading is crucial for a fast First Contentful Paint (FCP).

Synchronous scripts cause the 'white screen of death' by blocking the main thread.

Understanding async and defer allows you to download scripts early without halting the rendering process, while ensuring that dependent scripts execute in the correct order.

How it works (The Timeline)

**Sync:** Parse HTML 🛑 → DownloadExecuteResume Parse HTML

**Async:** Parse HTML (while Download in parallel) 🛑 → Execute (as soon as downloaded) → Resume Parse HTML

**Defer:** Parse HTML (while Download in parallel) ✅ → Finish Parse HTMLExecute (in exact document order)

Try it

Watch the Construction Site Race Track. See how a bulldozer (HTML Parser) reacts to delivery trucks (Scripts) depending on the loading strategy.

HTML Parser0%
Network Download0%
JS Execution0%
Sync (Default): The browser hits the script, completely stops HTML parsing, downloads the script, and executes it. Only then does it resume parsing HTML.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens to HTML parsing when a standard (synchronous) `<script>` tag is encountered?
  2. 2You have three scripts that depend on each other (A before B before C). Which attribute should you use to download them in the background but maintain execution order?
  3. 3When is the best time to use the `async` attribute for a script?

Remember this

  • Default scripts block parsing AND downloading.
  • Async scripts download in parallel but block parsing to execute immediately.
  • Defer scripts download in parallel and wait for parsing to finish before executing.
  • Defer guarantees execution order. Async does not.

Done with this concept?

Mark it complete to track your progress. No login needed.