Async v defer script tag attributes

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2021-05-15

When optimizing my website's speed, I saw that my time to first content paint was terrible due to JavaScript scripts that blocked. This was because I loaded my site's JavaScript synchronously in the head of my HTML.

I needed to stop blocking, so I looked at async and defer attributes. Both cause the browser to download JavaScript parallel to the HTML, using parallel requests (therefore speeding up page load).

async executes the individual scripts the moment the files are downloaded (even if HTML document is not fully downloaded yet). It does not respect order the scripts were encountered in.

<script async src="script.js">

defer downloads the entire HTML doc first (not stopped at the script tag now) and then executes the scripts (in the order they were encountered) after the HTML is downloaded.

<script defer src="script.js">

Generally I would go with defer as the semantics are easier to reason about.


By default, start off a website using defer rather than adding it later in the process.