03 / 06

Difference between async and defer in script tags?

Understanding async vs defer in <script> tags

When including JavaScript in HTML using the <script> tag, the async and defer attributes control how and when the script is loaded and executed relative to HTML parsing.

Key Differences Between async and defer
  1. 1

    async:

  2. 2
    • The script is downloaded asynchronously while the HTML is being parsed.
  3. 3
    • Execution happens as soon as the script is ready, potentially before HTML parsing is complete.
  4. 4
    • Scripts with async do not guarantee execution order if multiple async scripts are included.
  5. 5
    • Ideal for independent scripts that do not rely on the DOM or other scripts.
  6. 6

    defer:

  7. 7
    • The script is also downloaded asynchronously, but execution is deferred until the HTML parsing is complete.
  8. 8
    • Maintains the order of execution if multiple defer scripts are included.
  9. 9
    • Ideal for scripts that depend on the fully parsed DOM.
Example Usage

In short: Use async for independent scripts where execution order doesn’t matter, and defer for scripts that need the DOM fully loaded and/or must execute in a specific order.