What is the difference between async and defer in JavaScript?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #DOM #Performance

Brief Answer

  • async and defer are attributes for the <script> tag that affect how JavaScript loads and executes:
    • 🔄 Regular script (no attributes): blocks HTML parsing until loaded and executed
    • ⏱️ defer: loads in parallel with HTML but executes only after HTML parsing is complete
    • 🏎️ async: loads in parallel with HTML and executes immediately after loading, interrupting HTML parsing

Full Answer

How Script Loading Works

When a browser loads an HTML page, it processes (parses) the HTML code sequentially. When encountering a <script> tag, by default the browser:

  1. Pauses HTML parsing
  2. Downloads the script
  3. Executes the script
  4. Resumes HTML parsing

This can significantly slow down page rendering, especially if scripts are large or loaded from a slow server.

The async Attribute

<script async src="script.js"></script>
  • ✅ Loads asynchronously (in parallel with HTML parsing)
  • ⚠️ Executes immediately after loading, interrupting HTML parsing
  • 🔀 Execution order not guaranteed (first to load, first to execute)
  • 🚫 Doesn’t wait for the DOM tree or other scripts

The defer Attribute

<script defer src="script.js"></script>
  • ✅ Loads asynchronously (in parallel with HTML parsing)
  • ✅ Executes after HTML parsing is complete, but before the DOMContentLoaded event
  • ✅ Maintains execution order of scripts (as specified in HTML)
  • ✅ Guarantees DOM tree availability during execution

Comparison Table

CharacteristicRegular Scriptasyncdefer
Blocks HTML parsing during downloadYesNoNo
Blocks HTML parsing during executionYesYesNo
Execution order guaranteedYesNoYes
Waits for DOM before executionNoNoYes
When it executesImmediatelyAfter loadingAfter HTML parsing

Usage Example

<!-- Analytics: doesn't depend on DOM, order doesn't matter -->
<script async src="analytics.js"></script>
 
<!-- UI library: needs DOM and order matters -->
<script defer src="ui-framework.js"></script>
<script defer src="app.js"></script>

When to Use Each

  • async: for independent scripts that don’t need the DOM or other scripts

    • Analytics (Google Analytics)
    • Trackers
    • Social media widgets
  • defer: for scripts that need the fully built DOM or depend on other scripts

    • Main application code
    • UI libraries
    • Scripts that manipulate the DOM
  • No attributes: when the script must execute before the page is displayed

    • Critical code
    • Polyfills for older browsers