Programming Tutorials

async vs defer in JavaScript - When to use them?

By: Linda Ng in Javascript Tutorials on 2023-04-04  

Both async and defer are attributes that can be added to a script tag in HTML to control how the script is loaded and executed in the web page. Here are the differences between the two:

  1. Execution:

    • With defer, the script is executed only after the HTML parsing is complete.
    • With async, the script is executed as soon as it is available, regardless of whether or not the HTML parsing is complete.
  2. Order of Execution:

    • With defer, the order of execution of the scripts is maintained in the order they are specified in the HTML.
    • With async, there is no guarantee of the order of execution of the scripts.
  3. Blocking:

    • With defer, the HTML parsing is not blocked while the script is being downloaded and executed.
    • With async, the HTML parsing is blocked while the script is being downloaded and executed.

When to use which one:

  • Use defer when the script does not depend on any other scripts or the DOM, and you want to maintain the order of execution of the scripts.
  • Use async when the script is independent and can run in any order, and you want to speed up the loading of the page by downloading the script asynchronously.

It is also worth noting that both async and defer are not supported in all browsers, so it is important to test your code to ensure it works as expected.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)