If a third-party script is slowing down your page load, you have two options to improve performance:
- Remove it if it doesn't add clear value to your site.
- Optimize the loading process.
This post explains how to optimize the loading process of third-party scripts with the following techniques:
- Using the
asyncordeferattribute on<script>tags - Establishing early connections to required origins
- Lazy loading
- Optimizing how you serve third-party scripts
Use async or defer
Because synchronous scripts delay DOM construction and rendering, you should always load third-party scripts asynchronously unless the script has to run before the page can be rendered.
The async and defer attributes tell the browser that it can go on parsing
the HTML while loading the script in the background, then execute the script
after it loads. This way, script downloads don't block DOM construction or page
rendering, letting the user see the page before all scripts have finished
loading.
<script async src="script.js">
<script defer src="script.js">
The difference between async and defer attributes is when the browser
executes the scripts.
async
Scripts with the async attribute execute at the first opportunity after they
finish downloading and before the window's
load event. This means
it's possible (and likely) that async scripts won't run in the order in which
they appear in the HTML. It also means they can interrupt DOM building if they
finish downloading while the parser is still at work.