Async vs Differ in js

Misconception about the Script tag

Most people assume that the script tag should come before the closing body tag, as shown below:

This assumption is due to how the browser parses (loads) HTML.

However, you can place the script tag anywhere within the HTML document. For instance, you can put it within the header tag or immediately after the opening body tag.

How the browser parses HTML code

Parse means analyzing and converting program files into a format that is easy for the runtime environment (browser) to work with. Here, a program file can be an HTML file or a JavaScript file.

Parsing of an HTML file usually involves tokenization and tree construction.

Tokenization is the dividing of HTML opening tags, closing tags, attribute names, and values into units called tokens.

Tree construction involves building the Document Object Model (DOM) using tokens.

When the browser parses HTML code and comes across a script tag, the browser pauses the execution process.

The browser then downloads the content of the script and continues parsing the HTML code.

However, if you have an HTML file with many script tags within the header tag or body tag. Those tags may cause a significant delay in parsing the HTML file.

The delay occurs because the browser pauses the parsing of the HTML file in each script tag. Then the browser requests the content of the script tag. The HTML content below the script tag is, therefore, blocked.

The parsing of the HTML file can then continue after the content of the script tag is downloaded.

The image below gives a better understanding of normal HTML parsing:

defer

The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built.

Here’s the same example as above, but with defer:

async

Using async attribute downloads the script files asynchronously during HTML parsing ( in the background). After it finished downloading, only then it paused the HTML parsing and start executing the script file but before the window’s load event.