JavaScript Interview Question #159

What is the difference between defer and async on script elements?

Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced

Quick Interview Answer

Both attributes allow an external classic script to be downloaded without blocking HTML parsing in the normal way. An async script executes as soon as it is available, so execution order relative to other async scripts is not guaranteed.

Detailed Explanation

Both attributes allow an external classic script to be downloaded without blocking HTML parsing in the normal way. An async script executes as soon as it is available, so execution order relative to other async scripts is not guaranteed.

A defer script executes after HTML parsing and, for classic deferred scripts, preserves document order. ES module scripts are deferred by default in important respects, although module loading has its own dependency behavior.

Code Example

<!-- Executes when available; order is not guaranteed -->
<script async src="analytics.js"></script>

<!-- Executes after parsing; deferred scripts preserve order -->
<script defer src="vendor.js"></script>
<script defer src="app.js"></script>

<!-- Modules are deferred by default -->
<script type="module" src="main.js"></script>