What does async do in <script>?
Definition
asyncis 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
<script src="app.js"></script>What the browser does:
- Starts reading the HTML.
- Encounters
<script>. - Stops parsing the HTML.
- Loads
app.js. - Executes
app.js. - Continues with the rest of the HTML.
So a regular <script> blocks the page load until it finishes executing.
2. What async does
<script src="app.js" async></script>Now:
- The browser keeps loading the HTML.
- It loads
app.jsin the background, in parallel. - As soon as
app.jshas 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
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
| Attribute | When the script runs | Order | Blocks HTML | When to use |
|---|---|---|---|---|
| (no attribute) | Immediately when encountered | in order | Yes | Old inline code |
async | Right after loading | random | Can interrupt | Independent scripts (analytics, ads) |
defer | After the DOM is built | in order | No | The 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
<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
<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:
<head>
<script src="vendor.js" async></script>
<script src="main.js" defer></script>
</head>Summary
| Property | async | defer |
|---|---|---|
| Loads in parallel with HTML | Yes | Yes |
| Executes as soon as it's loaded | Yes | No |
| Waits for the DOM to be ready | No | Yes |
| Preserves script order | No | Yes |
| Blocks HTML parsing on execution | Can | No |
| Ideal for | Independent 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 readyA concise answer to help you respond confidently on this topic during an interview.