DEV Community

Cover image for Learn async v/s defer attributes of Script in JavaScript
Manish Mandal
Manish Mandal

Posted on

Learn async v/s defer attributes of Script in JavaScript

Hello Dev community!👋 I hope you're having a great day and staying safe during these challenging times🫡. Let's dive in our topic and I am sure I will definitely make you comfortable with async and defer. Let's dive in and explore how these powerful attributes can help boost your website's performance!"

What is async and defer?

Both "async" and "defer" are JavaScript characteristics that can be added to the script tag in an HTML document. They enable asynchronous script loading, which can improve website performance by lowering page load times.

Now you might have a question, how it reduces page loading?🧐

When a script is loaded synchronously (that is, without the "async" or "defer" attribute), the browser must load and run the script before proceeding to render the rest of the page. This can cause the page to "freeze" while the script is loading, resulting in slower page load times and a negative user experience.
When a script is loaded asynchronously using the "async" or "defer" attributes, the browser can continue to load and render the remainder of the page while the script is loading in the background. Because the page can be displayed to the user more rapidly, even while the script is still loading, this can result in speedier page load times.

Image description

When script tag does not have defer or async then it is executed synchronously, this means that the parsing of the HTML document will be paused and script file is fetched and after fetching it is executed then after again the HTML document starts parsing again.

Image description

When script tag has async attribute, both HTML document parsing and script file downloading happens parallelly and once Script file is downloaded then the HTML parsing is paused and script file is executed and after execution of script file again the HTML document started parsing.

Image description

When script tag has defer, the HTML is completely parsed along with the Script file is downloaded, After completely parsing of HTML document the Script file is executed.

CONCLUSION

In general, defer is preferred when there is no need of the script to be executed immediately after fetching but rely on other resources or scripts to be loaded first, and use async for scripts that can be executed independently and do not rely on other resources. However the optimal approach may upon their use case.

Top comments (0)