skip to content
Emmet Delaney

Async vs Defer - what to use, when.

/ 3 min read

Not a lot of people know that there are script attributes in html that can tell the browser how and when to download a script. This can be great for building a better experience for your end user. While async and defer may seem like minor tweaks, they can have a major impact on your website’s performance. Let’s unravel them both:

Async: Give It To Me Now

How it works: Async scripts download in the background without holding up the main thread. They can jump in and execute as soon as they’re ready, regardless of where they are in the HTML.

Best for:

  • Scripts that don’t rely on other scripts or the DOM (Document Object Model) to function.
  • Analytics scripts, ads, or social media widgets that can load independently.
  • Situations where execution order doesn’t matter.
<script async src="analytics-library.js" />

Defer: I’m not in a rush, when ever it’s ready

How it works: Defer scripts also download in the background, but they wait until the entire HTML document is parsed before stepping in. This can be extremely beneficial as we can render the markup of the page quickly without waiting for a script. They execute in the order they appear in the HTML, this also provides us with idempotency.

Best for:

  • Scripts that need the DOM to be fully loaded before they can do their thing.
  • Many interactive features, like form validation or dynamic content updates.
  • Cases where the order of script execution is crucial.
<script defer src="form-validation-logic.js" />

Choosing what, when: Async or Defer?

Which one should you use? Here’s a simple guideline to help you decide:

Need it ASAP? If a script is essential for the initial rendering of your page (e.g., a script that dynamically adds content), async is your go-to.

Can it wait? If a script is not critical to the initial display (e.g., a script that adds fancy animations or interactive elements), defer is your friend.

The Script Tag: Where to Put It?

Remember you were told to put script tags at the bottom of the <body>? This was to prevent them blocking the main thread but we don’t need to do this anymore! With defer, you can place your scripts anywhere in your HTML without fear of blocking the main thread. So, go ahead and group your script tags where-ever you want and apply async and defer as necessary.

The Power of Optimization: Your Website’s Secret Weapon

Optimizing JavaScript loading is a small step that can yield huge rewards. By using async and defer, you’ll be on your way to a faster, smoother, and more engaging website experience. And who knows, Our Lord and Saviour Google might also give you a nod and boost your search ranking too!