Table of Contents
In general, the async attribute is a good choice for scripts that do not need to interact with the DOM, such as scripts that load images or videos. The defer attribute is a good choice for scripts that need to interact with the DOM, such as scripts that initialize widgets or add event listeners. Omit both if your script makes massive changes to the visible viewport.
It is important to note that async scripts may fire in an unpredictable order, as they execute as soon as they are available, regardless of their order in the HTML document. If scripts depend on one another, using async may cause dependency errors.
Using defer is beneficial for scripts that rely on the DOM and need to be executed in a specific order, as it ensures that the necessary DOM elements are available when the script runs. This can be advantageous for scripts that perform DOM manipulation or have dependencies on other scripts.
|Attribute||When the script is loaded||When the script is executed|
| ||In the background||Before constructing the DOM|
| ||In the background||Immediately after loading|
| ||In the background||After the rest of the page has been parsed, in the order that it appears in the HTML|
How do async and defer improve Page Speed?
- Use asynchronous (async) for independent scripts that do not rely on the DOM and can be executed out of order.
- Use deferred (defer) for scripts that depend on the DOM and need to execute in a specific order, especially when performing DOM manipulation.
Please note that the effectiveness of using sync, async, or defer attributes may vary based on the specific context and content of the website. Regular testing and performance analysis are crucial to fine-tune the page loading strategy and ensure optimal results for different scenarios.
Taking it a step further, load scripts on demand
Async and defer can speed up a page by not blocking the parser, but it's important to note that 'deferring scripts' will not solve all your issues. For example, the largest contentful paint element is vulnerable to network and CPU competition caused by deferred and async scripts. The interaction to next paint is also affected by scripts that execute early during page load. That's why, whenever possible, you should load scripts on demand to have more control over their impact on page performance. Curious? Read how we load scripts on demand
I help teams pass the Core Web Vitals:
A slow website is likely to miss out on conversions and revenue. Nearly half of internet searchers don't wait three seconds for a page to load before going to another site. Ask yourself: "Is my site fast enough to convert visitors into customers?"