Skip to main content

What does the async attribute do on <script>?

The async attribute on the <script> tag makes the browser load and run the script asynchronously, that is, in parallel with loading the HTML document, without waiting for the page to finish building.


1. How

If you include a regular script:

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

The browser:

  1. Stops reading the HTML;
  2. Loads app.js;
  3. Runs it;
  4. Then continues building the page.

Drawback: the page "freezes" while the script loads.


2. What async does

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

The browser:

  1. Loads the HTML and app.js at the same time;
  2. Once the script loads, runs it immediately, without waiting for the HTML to finish;
  3. After execution, continues building the page.

This speeds up loading because the HTML and JS do not block each other.


3. When to use async

async suits scripts that do not depend on the DOM or other JS files, for example:

  • analytics counters (Google Analytics, Mixpanel);
  • ad blocks;
  • widgets or trackers that just collect data.

Example:

html
<script src="https://www.googletagmanager.com/gtag/js" async></script>

4. Difference between async and defer

AttributeWhen it runsKeeps orderUsed for
no attributeImmediately during loading (blocks HTML)YesSmall inline scripts
asyncAs soon as loaded, without waiting for HTMLNoIndependent scripts
deferAfter the HTML fully loadsYesScripts that work with the DOM

5. Comparison example

html
<!-- async --> <script src="analytics.js" async></script> <!-- defer --> <script src="main.js" defer></script>
  • analytics.js loads and runs as soon as it is ready (at an arbitrary moment).
  • main.js waits until the page fully loads, and only then runs.

Summary:

PropertyValue
PurposeAsynchronous loading and execution of a script
When it runsAs soon as the script loads
Delays page buildingNo
Execution orderUnpredictable
Ideal forIndependent or external scripts

In simple terms: async tells the browser:

"Download this script without stopping the page, and run it as soon as it is ready".

This speeds up the site's loading if the script does not depend on other parts of the page.

Short Answer

Interview ready
Premium

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