defer first we need to understand how the HTML is parsed.
HTML is parsed from top to bottom and if there is an
<img src="img.jpeg" /> tag in between it starts downloading the image in the background and the parsing will continue till it reaches the end.
<script src="script.js"></script> tag in between the script file gets downloaded and it stops HTML parsing until it executes the script.
defer attributes allow us to modify how this flow works.
In Normal parsing HTML file is parsed from top to bottom and when it reaches the
script tag it stops HTML parsing and downloads the script file and executes the script file, after downloading and executing it then continues parsing the HTML file.
Note: When you're not using the
defer attribute it is advised that you should use the
<script></script> tag before the
</body> closing body tag.
async parsing HTML file is parsed from top to bottom and when it reaches the
script tag instead of stopping, script file is downloaded in the background and it continues to parse the HTML file
While the script file is being downloaded in the background, as soon as the script file is downloaded, HTML parsing is stopped and script file is executed and then it continues parsing the HTML file till it reaches the end.
async attribute can run anytime, there is no guarantee for when it runs, and it can run in any order because they are just downloaded in the background asynchronously, and as soon as they are done downloading they run immediately.
<script src="script.js" async></script>
defer attribute is very similar to
async parsing, HTML file is parsed from top to bottom and when it reaches the
script file gets downloaded in the background and HTML parsing continues but instead of executing the script file after getting downloaded it waits until the entire page of HTML is parsed before it actually executes the script file.
Execution is deferred at the end with
<script src="script.js" defer></script>
defer when the order of execution of scripts is important.
async when the order of execution of scripts is not important.
defer are the great script tag attributes that allow you to speed up the page loading.
defer have one common thing: downloading of such scripts doesn’t block page rendering. So the user can read page content and get acquainted with the page immediately.
async attribute blocks the parsing of the page.
defer attribute never blocks the parsing of the page.
|Execution of scripts can be non-sequential.
|Execution of scripts is sequential.
|Execution of scripts leads to pausing of HTML document parsing.
|Execution of scripts is done when HTML document is completely parsed.
Thank you for making it till the end!