What is the difference between the async and defer attributes in the script tag?
sobes.tech AI
Answer from AI
The attributes async and defer on the <script> tag control the loading and execution of JavaScript to prevent blocking page rendering:
-
async— the script loads asynchronously in parallel with HTML parsing and executes immediately after loading, without waiting for parsing to finish. The execution order ofasyncscripts is not guaranteed. -
defer— the script also loads in parallel with parsing, but execution is deferred until the entire HTML is fully parsed. Scripts withdeferare executed in the order they appear in the document.
Example:
<script src="script1.js" async></script>
<script src="script2.js" defer></script>
script1.js may execute before or after, but script2.js will definitely execute after parsing and after other defer scripts in order.
Use defer for scripts that depend on the DOM, and async for independent scripts, such as analytics.