Third-Party Script Optimization
Third-party scripts are one of the most common causes of poor INP (slow interactions) and unstable pages. The goal is not "zero scripts". The goal is: load only what you need, only where you need it, and as late as the business allows.
Step 1: Audit Third-Party Cost
On a representative page, list third-party origins and what they do:
- analytics / tag managers
- ads
- chat widgets
- video and maps embeds
- social sharing / comments
Step 2: Remove or Replace
- Remove tools you do not use.
- Replace heavy embeds with lightweight facades (YouTube "lite" embeds, static map placeholders).
- Prefer loading scripts only on the pages that need them.
Step 3: Load Strategy
You have three broad options:
| Strategy | When to use | Trade-off |
|---|---|---|
| Normal load | required for business-critical tracking | worst performance impact |
| Async/defer | many vendor scripts support it | still executes on load |
| Delay until interaction/consent | chat widgets, heatmaps, some analytics | may reduce tracking fidelity |
caution
Do not delay scripts that must fire on page load for revenue tracking unless the business explicitly accepts the trade-off.
Example: Load a Script on First Interaction
Lazy-load a third-party script on first interaction
<script>
(function () {
function load(src) {
var s = document.createElement('script');
s.src = src;
s.async = true;
document.head.appendChild(s);
}
function onFirstInteraction() {
load('https://example-third-party.com/widget.js');
window.removeEventListener('scroll', onFirstInteraction);
window.removeEventListener('pointerdown', onFirstInteraction);
window.removeEventListener('keydown', onFirstInteraction);
}
window.addEventListener('scroll', onFirstInteraction, { passive: true });
window.addEventListener('pointerdown', onFirstInteraction);
window.addEventListener('keydown', onFirstInteraction);
})();
</script>
Verification
- The page is usable before third-party scripts load.
- Critical interactions work on first tap/click.
- Analytics/conversion events still fire as intended.
Checklist
- Third-party origins audited.
- Unused tools removed.
- Heavy embeds replaced with facades.
- Non-critical scripts delayed or scoped to specific pages.