Async vs Defer in JavaScript

Async vs Defer in JavaScript

Hi everyone! I hope all is well with you. We'll look into an intriguing Javascript topic in this article. When adding external JavaScript files into HTML documents, the characteristics async and defer are utilized. They have an impact on how the script loads and runs in the browser. Let's study them in greater detail.

Typical Conduct

Typically, we use the <script> tag to connect our HTML page to external JavaScript. JavaScript <script> elements were traditionally inserted within the HTML document's <head> section. But doing so causes the HTML processing to stop until the JavaScript file is downloaded and run, which slows down how quickly pages load. These days, we usually prefer to retain the <script> tag after the <body> element's contents have fully loaded.

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

This is how script execution and HTML parsing work.


Script Performance Image

Async

A script that is included with the async attribute instructs the browser to download it asynchronously while it parses the HTML text. Without impeding HTML processing, the script downloads in the background.

The script runs asynchronously, so it can begin running as soon as it is downloaded and end before the HTML document has finished processing.

<script src="example.js" async></script>

Regardless of the order in which they appear in the page, if numerous scripts are loaded asynchronously, they will start running as soon as they have finished downloading. It comes in handy when the script doesn't rely on other scripts or the DOM being fully loaded.


Async Image

Defer

The defer property instructs the browser to download the script asynchronously while it parses the HTML document when we include it. But the script doesn't start running until the HTML document has been parsed.

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

Scripts that have the defer attribute applied to them will run in the document's order of appearance. It comes in handy when the script depends on the DOM being fully parsed or when the sequence in which the script is executed matters.


Defer Image

Conclusion

The HTML parsing process can proceed without waiting for the script to download thanks to both async and defer.

The timing of the script's execution determines the difference: When a script is used with async, it starts running as soon as it is downloaded, maybe even before the HTML document has finished parsing. By using a defer, the script runs only after the HTML document has been fully parsed, but prior to the event known as DOMContentLoaded.

One thing to keep in mind is that defer is used when script execution order needs to be maintained or when the script depends on the DOM structure, while async is only appropriate for independent scripts.

I sincerely hope you found this article interesting, and please remember to like it!