Sobes.tech
Middle+

What is the difference between the async and defer attributes in the script tag? How do they affect the loading and execution of JavaScript?

sobes.tech AI

Answer from AI

The async and defer attributes on the <script> tag affect the loading and execution of external JavaScript files, optimizing page performance:

  • async

    • The script loads asynchronously, in parallel with HTML loading.
    • Executes immediately after loading, without waiting for full HTML parsing.
    • The execution order of async scripts is not guaranteed if multiple are used.
    • Suitable for independent scripts that do not depend on DOM or other scripts.
  • defer

    • The script also loads asynchronously, in parallel with HTML.
    • Executes only after the complete loading and parsing of the HTML document.
    • Scripts with defer are executed in the order they appear in the document.
    • Suitable for scripts that interact with the DOM and should run after it is ready.

If neither async nor defer is specified, the script loads and executes synchronously, blocking HTML parsing.

Example usage:

<script src="script1.js" async></script> <!-- loads and executes immediately after loading -->
<script src="script2.js" defer></script> <!-- loads in parallel, executes after parsing -->
What is the difference between the async and defer… - sobes.tech