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:
- Stops reading the HTML;
- Loads
app.js;
- Runs it;
- Then continues building the page.
Drawback: the page "freezes" while the script loads.
<script src="app.js"></script>app.js;2. What async does
<script src="app.js" async></script>The browser:
- Loads the HTML and
app.jsat the same time; - Once the script loads, runs it immediately, without waiting for the HTML to finish;
- 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:
<script src="https://www.googletagmanager.com/gtag/js" async></script>4. Difference between async and defer
| Attribute | When it runs | Keeps order | Used for |
|---|---|---|---|
| no attribute | Immediately during loading (blocks HTML) | Yes | Small inline scripts |
async | As soon as loaded, without waiting for HTML | No | Independent scripts |
defer | After the HTML fully loads | Yes | Scripts that work with the DOM |
5. Comparison example
<!-- async -->
<script src="analytics.js" async></script>
<!-- defer -->
<script src="main.js" defer></script>analytics.jsloads and runs as soon as it is ready (at an arbitrary moment).main.jswaits until the page fully loads, and only then runs.
Summary:
| Property | Value |
|---|---|
| Purpose | Asynchronous loading and execution of a script |
| When it runs | As soon as the script loads |
| Delays page building | No |
| Execution order | Unpredictable |
| Ideal for | Independent 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 readyA concise answer to help you respond confidently on this topic during an interview.