This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for Interview Question on BFE.dev
119. What is the difference between `async` and `defer` on script tag?

In short, the difference between async and defer on a script tag is that:

  • async tells the browser to download the script in the background and execute it as soon as possible, without stopping the parsing of the HTML page. This means that the script can be executed before the page is fully loaded, but it also means that the order of execution of multiple async scripts is not guaranteed.
  • defer also tells the browser to download the script in the background, but it defers the execution until the HTML parsing is complete, just before the DOMContentLoaded event. This means that the scripts will be executed in the order they are defined, and won't block the rendering of the page.

So, in general, if the script does not rely on the DOM or other external resources, async could be a good option to speed up the loading time. Otherwise, if the script needs to access the DOM, defer is a safer choice as it ensures that the DOM is ready to be manipulated.