Skip to main content

What does async do in <script>?

Definition

async is an attribute for <script> that tells the browser:

"Load this script asynchronously (in parallel with the HTML) and run it right after it loads, without waiting for the DOM or other scripts."


1. How a regular <script> works

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

What the browser does:

  1. Starts reading the HTML.
  2. Encounters <script>.
  3. Stops parsing the HTML.
  4. Loads app.js.
  5. Executes app.js.
  6. Continues with the rest of the HTML.

So a regular <script> blocks the page load until it finishes executing.


2. What async does

javascript
<script src="app.js" async></script>

Now:

  1. The browser keeps loading the HTML.
  2. It loads app.js in the background, in parallel.
  3. As soon as app.js has loaded, it executes it immediately, even if the HTML isn't finished yet.

That is:

  • loading is asynchronous,
  • execution is immediate,
  • the order relative to other scripts is not guaranteed.

3. Visually

javascript
HTML: |-----parsing-----|--------> JS: |---loading--|execution|

HTML and JS load in parallel, but JS execution can interrupt HTML parsing if the script finishes loading first.


4. Difference from defer

AttributeWhen the script runsOrderBlocks HTMLWhen to use
(no attribute)Immediately when encounteredin orderYesOld inline code
asyncRight after loadingrandomCan interruptIndependent scripts (analytics, ads)
deferAfter the DOM is builtin orderNoThe site's main code

The main idea:

  • async: "run as soon as you're ready, don't wait for anyone"
  • defer: "wait until the DOM is built, then run in order"

5. Example

javascript
<script src="analytics.js" async></script> <script src="main.js" defer></script>

analytics.js is independent, it can run right away main.js depends on the DOM, it runs after it's built


6. Example with several async scripts

javascript
<script src="a.js" async></script> <script src="b.js" async></script>

They can execute in any order, depending on which file finishes loading first.


7. Using it together with <head>

async and defer only work for external scripts (src="..."). Inline scripts (<script>...</script>) ignore these attributes.

An example of the correct setup:

javascript
<head> <script src="vendor.js" async></script> <script src="main.js" defer></script> </head>

Summary

Propertyasyncdefer
Loads in parallel with HTMLYesYes
Executes as soon as it's loadedYesNo
Waits for the DOM to be readyNoYes
Preserves script orderNoYes
Blocks HTML parsing on executionCanNo
Ideal forIndependent scripts (analytics, ads, widgets)The site's main logic

A simple way to remember it:

  • async: "load and run as fast as possible"
  • defer: "load ahead of time, but wait until the DOM is ready"

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.