Difference Between script, async and defer
The <script> tag is used to connect JavaScript files to HTML documents. Depending on async and defer attributes, script loading and execution behavior changes.
script (without attributes)
- Downloaded and executed immediately as soon as HTML parser reaches it.
- Blocks HTML parsing until script execution completes.
- Suitable only for small scripts at the end of the page.
<script src="script.js"></script>
script async
- Script loads asynchronously and executes immediately once loaded.
- Doesn't guarantee execution order (if multiple async scripts).
- Suitable for third-party scripts (analytics, ads).
Behavior:
- Doesn't block HTML parsing during loading.
- Can block rendering during execution.
script defer
- Script loads asynchronously, but executes after full HTML load.
- Preserves order of script connections.
- Ideal for most modern applications.
<script src="script.js" defer></script>
Behavior:
- Doesn't block HTML.
- Executes after HTML parsing completes, but before
DOMContentLoadedevent.
Comparison Table
| Attribute | Loading | Execution | Blocks Parsing? | Preserves Order? |
|---|---|---|---|---|
(no attributes) | immediately | immediately after load | Yes | Yes |
async | parallel | immediately after load | No (but can block execution) | No |
defer | parallel | after HTML parsing | No | Yes |
Tip:
If you're not using type="module", always prefer defer for internal scripts — it doesn't block HTML and preserves order.