Sobes.tech
Middle

What is the difference between <script>, <script async>, and <script defer>?

sobes.tech AI

Answer from AI

When using a regular <script> tag, the browser stops parsing HTML, loads and executes the script, then continues parsing.

<script async> loads the script in parallel with HTML parsing. The script executes immediately after it is loaded and before parsing is complete. The execution order of asynchronous scripts is not guaranteed.

<script defer> also loads the script in parallel with HTML parsing. The script execution is deferred until the entire HTML is parsed. Scripts with defer are executed in the order they appear in the document.

Attribute HTML Parsing Script Loading Script Execution Dependency on Order
<script> Pauses parsing Blocks Blocks Yes
<script async> Continues Does not block Does not block No
<script defer> Continues Does not block Does not block Yes

Example:

<script src="script1.js"></script>
<script async src="script2.js"></script>
<script defer src="script3.js"></script>

<!--
  Normal:<script src="script1.js"></script>
  The browser parses HTML up to this tag,
  pauses parsing, loads script1.js,
  executes script1.js, then continues parsing.

  Asynchronous:<script async src="script2.js"></script>
  The browser continues parsing HTML,
  loads script2.js in parallel.
  Once script2.js is loaded, it can execute
  at any moment, interrupting parsing, before
  HTML parsing is complete.

  Deferred:<script defer src="script3.js"></script>
  The browser continues parsing HTML,
  loads script3.js in parallel.
  script3.js executes only after
  the entire HTML is fully parsed.
  If there are multiple scripts with defer, they will execute
  in the order they are specified in HTML.
-->