As I mentioned earlier, in order to understand the impact of Deferred scripts, we first need to understand the concept of the defer & async attributes in addition to the differences between them.
- Normal Execution
- Defer = Deferred
- Async = Asynchronous
Before we take a look at the more advanced way, let’s understand the norma way without special attributes added to it.
This is the default way JS scripts o be loaded if you didn’t specify otherwise.
The native behavior of JS is to literally stop the HTML Parsing of the page in order to run, fetch and execute the commands you have written in that script file. Prolonging the Time To First Byte(TTFB). That’s not good for us. It ultimately results in a slower website.
JS Defer vs Async
Now that we understand the native behavior and its impact on our website. We can move on and dive into the 2 remaining methods of implementing and loading scripts.
<script async src="script.js"></script>
In this case, the script will be executed whenever it’s ready. Meaning, the parsing of HTML elements won’t have to stop.
<script defer src="script.js"></script>
Simply put, this attribute tells the browser to delay all script execution and execute it only when the DOM is fully loaded. Moreover, something important to keep in mind about both of these ways is that in both cases, the script files are downloaded alongside the parsing of the DOM.
But, with Async, HTML Parsing stops while the scripts run. However, With defer, the HTML parsing doesn’t stop This is due to the simple fact that the defer attribute tells the browser to execute the script ONLY after the DOM is loaded.
When Do I use each one of them?
|When I need to make use of DOM Elements – defer|
|No external dependencies inside your script – async|
|if the scritp is before the </body> tag – no sense in using defer or async , most of the DOM will be parsed by then.|
|If the script is small – individual per case decision – make use of your judgment in consideration of what code you run there and think about its impact and then decide.|
|Scripts implemented in the <head> tag – defer|
These are key examples of usage with these attributes. Despite that, there are more cases where one must think about using one of them in a more “delicate” manner. However, that’s a subject for another article.
If you have any more thoughts, questions or feedback feel free to write it in the comment section below! Finally, if you have more creative examples of defer & async usage, feel free to share them.