How things work without these attributes?
The web browser starts parsing the HTML and it gets paused when the script tag is reached (here I am strictly talking about external JS Files and not the inline scripts). At that point, parsing of HTML is blocked and browser makes a request to fetch/download the respective script file. Once the script is fetched, it gets executed and then HTML parsing resumes again.
How to use ‘async’ attributes?
With async (asynchronous) attribute, the HTML parsing continues until the browser fetches the script file over the network so parsing and script fetching happens in parallel (as shown in the figure below). Once the scripts are available in the browser, HTML parsing is paused and scripts are executed. Once the execution is complete, HTML parsing continues.
So this is an asynchronous way of downloading scripts. Lets look at the ‘defer’ attribute now.
How to use ‘defer’ attributes?
The word ‘defer’ in English means to ‘hold back’. So with defer attribute mentioned in the script tag, the script files are downloaded in parallel while the HTML parsing continues. But the execution is deferred until the HTML parsing is done. In simple words, the downloaded scripts are executed only when the browser finishes its HTML parsing.
Now that you have learnt how to use async and defer attributes, the important question is when to use them?
When to use ‘async’ and when to use ‘defer’?
Well, you can use async attribute when your page does not depend on the script files (for example analytics). Why? Because async cannot guarantee the order in which your scripts files will be downloaded. So if there is any dependency amongst your script files, it may break your code. In such cases you can use defer attribute.
Now that we have async and defer attributes, we can put our script references in head tag and as this allows your scripts to be downloaded asap without blocking your browser. If you are not using these keywords, make sure to put it at the bottom before closing your body tag. This will ensure that the HTML parser is not blocked by the scripts.