Abhay Jain

Dec 23, 2020

2 min read

Script Execution: Normal, Asynchronous, and Deferred

Loading several JavaScript files on a page, as this will interfere with the time to first paint even if the document is not actually dependent on those files.

Fortunately, the <script> element has two attributes, async and defer, that can give us more control over how and when external files are fetched and executed.

Let's explore it one by one...

Normal Execution

Take, for example, this script element located somewhere in the middle of the page -

<html>
<head> ... </head>
<body>
...
<script src="script.js">
....
</body>
</html>

The HTML parsing is paused for the script to be fetched and executed, thereby extending the amount of time it takes to get to the first paint.

The async Attribute

<script async src="script.js">

This attribute is only available for externally located script files. When an external script has this attribute, the file can be downloaded while the HTML document is still parsing. Once it has been downloaded, the parsing is paused for the script to be executed.

The defer Attribute

<script defer src="script.js">

Like an asynchronously loaded script, the file can be downloaded while the HTML document is still parsing. However, even if the file is fully downloaded long before the document is finished parsing, the script is not executed until the parsing is complete.