The async
and defer
attributes are used to specify the loading behavior of external scripts in an HTML document. They can be used to improve the performance of a webpage.
When there is no attribute for the
<script>
written, everything loads line by line, and nothing loads asynchronously. The HTML loading will stop to cater to the loading of the script which will then then execute entirely, and then the HTML will continue loading. It can make for a jarring user experience.The
async
attribute tells the browser to load the script 'asynchronously', meaning that it will be loaded in the background while the rest of the page continues to load. The script will be executed as soon as it finishes loading, and it can even interrupt the parsing of the page. This can be useful in saving time when the script is not critical to the initial rendering of the page and can be loaded in the background without affecting the user's experience.The
defer
attribute also tells the browser to load the script 'asynchronously' but to wait until the page has finished parsing before executing the script. This can be useful when the script depends on the content of the page and needs to be executed after the page has finished loading.
Both async
and defer
can be used to improve the performance of a webpage by allowing the browser to load the scripts in the background while the rest of the page continues to load, but they have different behaviors and are suitable for different use cases.