Tell about the defer and async attributes in the script tag. How do they differ?
sobes.tech AI
Answer from AI
The defer and async attributes on the <script> tag control the loading and execution of external scripts to improve page load performance.
-
async — the script loads asynchronously in parallel with HTML parsing and executes immediately after loading, without waiting for parsing to finish. This can lead to scripts executing in arbitrary order.
-
defer — the script also loads asynchronously, but execution is deferred until the entire HTML has been fully parsed. Scripts with defer are executed in the order they appear in the document.
If neither async nor defer is used, the script blocks HTML parsing until it is loaded and executed.
Example:
<script src="script1.js" async></script>
<script src="script2.js" defer></script>
Here, script1.js will load and execute as soon as it loads, possibly before the page is fully loaded. script2.js will load in parallel but execute after the HTML has been fully loaded and parsed.