Sync vs Defer in JavaScript

Sync vs Defer in JavaScript

Sync and defer are two attributes that can be used to modify the behavior of script tags in HTML. They affect how and when the browser downloads and executes the JavaScript code.

By default, when the browser encounters a script tag, it stops parsing the HTML document and waits for the script to download and run. This can cause delays in rendering the page, especially if the script is large or slow. To avoid this, sync and defer can be used to make the script load asynchronously, meaning that the browser can continue parsing the HTML while the script is being downloaded in the background.

The difference between sync and defer is that sync executes the script as soon as it is downloaded, while defer executes the script only after the HTML document is fully parsed. This means that sync scripts can still block the rendering of the page, while defer scripts do not. Another difference is that sync scripts do not guarantee the order of execution, while defer scripts preserve the order of the script tags.

Here are some examples of how sync and defer can be used in code:

  • To load a script asynchronously and execute it as soon as possible, use sync:
<script src="script.js" async></script>
  • To load a script asynchronously and execute it after the HTML document is parsed, use defer:
<script src="script.js" defer></script>
  • To load multiple scripts asynchronously and execute them in the order they appear in the HTML document, use defer for all of them:
<script src="script1.js" defer></script>
<script src="script2.js" defer></script>
<script src="script3.js" defer></script>
  • To load multiple scripts asynchronously and execute them as soon as possible, regardless of the order, use sync for all of them:
<script src="script1.js" async></script>
<script src="script2.js" async></script>
<script src="script3.js" async></script>
  • To load a script synchronously and block the HTML parsing until it is done, use neither sync nor defer:
<script src="script.js"></script>