Javascript defer vs async is a common question in Javascript interviews. Modern web applications deal with a lot of scripts. So, it is very important for a Javascript developer to know how to optimally load scripts on a webpage.

The interviewer might start with asking you questions around how do you load a script on a webpage. The discussion would generally lead to questions around defer vs async.

Before we jump onto the difference between defer and async, there are a few concepts that we should be clear on. These are discussed below:

HTML Parsing

When the browser receives an HTML document from the server, the first thing it does is start reading the HTML or in more technical terms, it starts parsing the HTML. The end result of parsing is the DOM (Document Object Model). For the page to be visible to the user, it’s important that the DOM is ready as soon as possible.

Phases of Script Loading

There are two important phases of script loading:

Script download

A script download happens when the browser makes a network request to fetch a javascript file. Download is an expensive operation. It contributes to the majority of the time taken to render a page.

Script execution

Script execution happens after the file has downloaded. The Javascript engine is responsible for executing the javascript.

Popular Ways of Loading Scripts on a Webpage

A good understanding of how external Javascript files are loaded on a webpage is required. Here are the most popular ways to do so:

In the head (without async or defer)

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

This is the most traditional way of loading scripts on the webpage. While parsing, when this line is encountered, the browser stops parsing, makes a request to get the javascript file. And once the javascript file has downloaded, it is executed. Only after that point, the browser can resume back HTML parsing.

Moreover, the script might try to access a DOM element that is not yet available, thus resulting in an error. This problem can however be avoided by using DOMContentLoaded as shown below. In this case, the execution will happen only after the DOM parsing has completed.

#javascript

Javascript defer vs async
1.25 GEEK