12 Javascript defer or async?
When adding interactivity to our web pages we heavily rely on JavaScript. But adding JavaScript comes with a price. The much feared render block. So let’s examine what render blocking is and why it’s happening.
Traditionally, scripts were added within the head tag. When the browser’s main thread was parsing the page it evaluated the script tag, it stopped the parsing process, downloaded the JavaScript resource and executed the script. This strategy led to slow renderings, as the parsing process was stopped every time.
Then developers tried to improve performance by moving the scripts to the very end of the source code, which delivered better results but led to other problems.
With HTML5 new attributes for script tags arrived to address this problem. Async and defer. Both tackle performance problems in a different way and neither guarantees a non blocking behaviour. This needs to be addressed in the script itself. But you do have more control about what happens when.
When using the async attribute, the JavaScript file gets downloaded asynchronously and then executed as soon as it’s downloaded.
When using defer, the JavaScript file gets also downloaded asynchronously. The key difference is, that it is executed when the document parsing is completed.
So, the advantage here is, that scripts will execute in the same order as they are linked in the HTML which is not guaranteed with async.
This makes defer the attribute of choice when a script depends on each other. Async is fine when you want a script to be executed early in the loading process.
- https://flaviocopes.com/javascript-async-defer/
- https://web.dev/efficiently-load-third-party-javascript/
Tomorrow follows: #13 Web Performance Timing APIs