Summary
The use of third-party scripts can have a significant impact on website performance. These scripts often operate in a blocking manner and can hinder page loading times. To reduce the time spent on these scripts, it is recommended to:
- Avoid using third-party scripts whenever possible
- Delay the loading of scripts until after user interaction
- Use async or defer attributes for scripts
- Preload connection to the script’s origin
Delaying the loading of scripts.
If the script in question is not a priority, meaning it can wait for user interaction or does not represent a vital functionality for the website, a recommendation is to delay its loading until the user interacts with the site. Each script may require a different strategy to delay its execution. Below is an example of a common strategy (source) to delay the script so that it is only executed after user interaction followed by a delay:Async and Defer in Scripts
The presence of a<script src="script.js">
tag causes a delay in the execution
of DOM loading. This is because the browser will respect the order of the
scripts to download and execute them.
If the script itself does not manipulate the DOM, it is a strong candidate to be
delayed using async. An async script will be downloaded asynchronously and then
executed at the first opportunity before the DOM is loaded:
Preload connection to the script’s origin
If possible, it is recommended to serve the script locally (in thestatic
folder). If the script is hosted on another domain, the recommendation is to use
prefetch to speed up the resolution of the script’s server DNS:
important: use preconnect only when necessary and for scripts with a significant impact.