⚡ defer vs async – Why They Matter When Loading JavaScript in <head>

If you've ever written HTML with JavaScript, you've probably used something like this:
<script src="main.js"></script>
But what if I told you this innocent-looking tag could block your page from loading quickly? 🐢 That’s where defer
and async
come in.
Let’s break it down clearly — when to use which, why it matters, and how they impact performance.
🧠 The Problem with Plain <script>
in <head>
By default, when the browser hits:
<script src="main.js"></script>
It stops building the page, downloads the script, and runs it immediately. That’s a render-blocking behavior — especially bad if you put it in the <head>
.
What happens? |
Browser stops parsing HTML |
Fetches the JS file |
Waits for it to load |
Executes it before continuing with HTML |
That delays showing content to the user. ⏳
✅ The Solution: defer
and async
Modern browsers give us two attributes to fix this:
<script src="main.js" defer></script>
<script src="main.js" async></script>
But they behave very differently.
🕓 defer
— Best for Most Scripts
“Load this script in the background, but wait until the HTML is fully parsed before running it.”
<head>
<script src="main.js" defer></script>
</head>
✔ How defer
Works:
Step | Description |
✅ Starts downloading the script right away | |
✅ Keeps parsing the HTML (doesn't block) | |
✅ Waits until DOM is fully parsed | |
✅ Then executes the script in order (if there are multiple scripts with defer ) |
👍 Use defer
when:
You want to include scripts in
<head>
without blocking the pageYour script depends on DOM elements
You’re loading multiple scripts that should run in order
⚡ async
— Best for Independent Scripts
“Load and run this script as soon as it’s ready — I don’t care about the rest of the HTML.”
<head>
<script src="analytics.js" async></script>
</head>
❗ How async
Works:
Step | Description |
✅ Starts downloading immediately | |
❌ May interrupt HTML parsing to execute | |
❌ Execution order is not guaranteed (if you have multiple async scripts) |
👍 Use async
when:
Your script doesn’t depend on the DOM (e.g., analytics, ads, trackers)
You don’t care about execution order
You want to load small, independent scripts fast
🔍 defer vs async vs nothing — Visual Comparison
Behavior | <script> | <script defer> | <script async> |
Blocks HTML parsing | ✅ Yes | ❌ No | ❌ No (but may interrupt) |
Waits for DOM to load | ❌ No | ✅ Yes | ❌ No |
Order preserved | ✅ Yes | ✅ Yes | ❌ No |
Good for DOM-dependent logic | ✅ Yes (but blocks) | ✅ Yes | ❌ No |
Best use-case | Legacy, blocking scripts | Most app scripts | Third-party tools |
✅ Final Recommendations
Use
defer
for your main JavaScript files.Use
async
only for scripts that don’t depend on anything else.Avoid plain
<script>
in the<head>
unless absolutely necessary.
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
