Course contentsShow
← Web Development
Lesson 2048 of 2,98237. Image and Asset OptimizationFree lesson

async vs defer for Script Loading

Learn the differences between async and defer attributes and when to use each for optimal loading.

async vs defer for Script Loading

You'll learn when to use async and defer attributes to load third-party scripts without blocking your page.

The Problem: Scripts Block the Parser

By default, when the browser encounters a <script> tag while parsing HTML, it stops everything, downloads the script, executes it, and only then continues parsing. This can significantly delay when users see content.

Two Solutions: async and defer

Both attributes tell the browser to download scripts in the background without blocking HTML parsing, but they differ in when scripts execute:

async: Execute ASAP

<script src="analytics.js" async></script>

Downloads in parallel, then executes immediately when ready (pausing the parser if still running). Scripts execute in whatever order they finish downloading, not document order. Perfect for independent scripts like analytics or ads that don't depend on anything else.

defer: Execute After Parsing

<script src="app.js" defer></script>

Downloads in parallel, but waits to execute until HTML parsing is completely finished. Multiple deferred scripts execute in the order they appear in the document. Ideal for scripts that need DOM to be ready or depend on each other.

Decision Guide

  • Neither attribute? Script blocks parsing — use for critical scripts only.
  • async? For independent third-party scripts that don't manipulate DOM or depend on other scripts.
  • defer? For your application scripts that need the DOM or must execute in a specific order.

Key Takeaway: Use async for independent third-party scripts that should run ASAP; use defer for scripts that need the full DOM or must maintain execution order.