Sobes.tech
Middle

Explain the attributes async and defer in the script tag. What are they and what is the difference?

sobes.tech AI

Answer from AI

The async and defer attributes on the <script> tag control the loading and execution of JavaScript files, affecting page performance and behavior.

  • async — the script loads asynchronously in parallel with HTML loading and executes immediately after loading, without waiting for the entire document to load. This is good for independent scripts that do not depend on the DOM or other scripts.

  • defer — the script also loads asynchronously, but its execution is deferred until the entire HTML has been fully loaded and parsed. Scripts with defer are executed in the order they appear in the document.

Main difference:

Attribute Loading Execution Execution order
async Asynchronously Immediately after script loads Not guaranteed
defer Asynchronously After HTML parsing In order of appearance in the document

If a script affects the DOM or depends on other scripts, it is better to use defer. If the script is independent and does not affect the DOM, you can use async.

Explain the attributes async and defer in the script… - sobes.tech