How to use async and defer keywords while loading external content on webpage

As the web is growing, there are lots of new features are added to the browsers in order to utilise the bandwidth and available processing power efficiently. It was a problematic situation where the browser used to make only one request at a time for loading the external content.

Now that we have got two new keywords for loading the external content efficiently It is worth sharing with everyone.
Note : At the time of writing this It’s only supported for scripts

defer keyword

[code language=”html”]
<script type="text/javascript" href="jquery.js" defer></script>
<script type="text/javascript" href="page.js" defer></script>

Usage – When there are scripts which are supposed to be run in the order they are actually referenced to the document. It allows the html loading even when the script is defined in <head> section To clarify more,

if there are two scripts lets call them jquery.js and page.js so even if the page.js is loaded first and jquery.js is still being loaded then also page.js will not be run since the execution type is specified as defer.

It should be used whenever the scripts are dependent on others, here in the example page.js usage the functions defined in jquery.

async keyword

[code language=”html”]
<script type="text/javascript" href="page.js" defer></script><!– large file –>
<script type="text/javascript" href="utilities.js" async></script><!– small file –>
Usage – When there are scripts which are supposed to be run as soon as they are downloaded.

Utilities.js can be an example here if it’s not dependent on any other script, Generally Utilities are independent

It should be used whenever the scripts are independent (doesn’t use anything defined in other scripts).



Leave a Reply

Your email address will not be published. Required fields are marked *