Describe the difference between <script>, <script async> and <script defer>

Answer

When including JavaScript in an HTML document, the behavior of how the script is loaded and executed can vary depending on the attributes used in the <script> tag. Below are the differences:

  1. <script> (default behavior):

Use case: When the script depends on the HTML or other scripts that must run in a specific order.

<script src="script.js"></script>
  1. <script async>:

Use case: For scripts that are independent of other scripts or the page content, such as third-party analytics or ads.

<script async src="script.js"></script>
  1. <script defer>:

Use case: When scripts need to wait for the full DOM to be parsed but must still execute in order.

<script defer src="script.js"></script>

Key Notes:

MDN Web Docs - script