What does the defer attribute do on <script>?
The defer attribute on the <script> tag delays the execution of JavaScript code until the browser has fully loaded and parsed the HTML document.
It lets you place scripts in <head> without risking "freezing" the page load.
1. The problem without defer
By default, if you include a script like this:
<script src="main.js"></script>the browser stops building the page,
loads and runs main.js, and only then continues reading the HTML.
This slows down the loading and rendering of content (especially if the script is large).
2. What defer does
If you add defer:
<script src="main.js" defer></script>The browser:
- Starts loading the script asynchronously (in parallel with the HTML);
- Does not stop page rendering;
- Runs the script only after the HTML is fully loaded, that is, once the DOM is ready.
Put simply:
defer= "download it ahead of time, but run it later, once everything is built".
3. When to use it
defer is ideal for scripts that work with page elements (the DOM):
<head>
<script src="menu.js" defer></script>
<script src="slider.js" defer></script>
</head>Both scripts run in the order they were included, after the HTML loads.
4. Difference from async
| Attribute | How it works | Execution order |
|---|---|---|
| no attribute | Stops the HTML load, runs immediately | As encountered |
async | Loads asynchronously and runs right after loading | Arbitrary order |
defer | Loads asynchronously, runs after the DOM is built | In inclusion order |
Summary:
| Property | Value |
|---|---|
| Purpose | Delays script execution until the HTML loads |
| Works only with | External files (<script src="...">) |
| Priority | Runs after the DOM is built |
| Execution order | Preserved as in the code |
| Advantage | Speeds up page loading and does not block rendering |
In simple terms:
defer tells the browser:
"Download this script now, but run it once the page has fully loaded".
This makes the site faster and prevents errors when JavaScript tries to access elements that are not yet in the DOM.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.