Third-Party Scripts Hurting INP? How to Prove and Fix It
Prove which third-party scripts hurt INP with DevTools and long-task data, then defer, delay or replace them, and show the before and after to stakeholders.
Kazi Khalid Hasan Tamim · BugViso Team
13 min read
Third-party scripts hurt INP because they run on the same main thread as your own code. Every analytics, chat, A/B testing and ad tag that executes during a tap adds to the input, processing or presentation delay.
Fixing it means finding which script owns the long task, then deferring, lazy-loading or isolating it.
This guide shows how to prove that cost on your own pages. Attribute slow frames to scripts with the Long Animation Frames API.
Confirm it by blocking one script at a time. Then apply the fix patterns below.
It doesn't publish a vendor-by-vendor benchmark, because the cost of a tag depends on its configuration and on your page; the numbers that matter are the ones you measure.
INP is one of the three metrics in what LCP, INP and CLS measure. For Tag Manager containers specifically, see Google Tag Manager performance, and for non-script causes see common causes of poor INP.
How to Measure the Main-Thread Cost of Each Tag
The target is Google's threshold: an INP of 200 ms or less at the 75th percentile is "good", above 500 ms is "poor". To find out how much of your INP each script owns, run a controlled comparison:
- Device: a mid-range Android phone, or Chrome DevTools with CPU throttling. Lighthouse's mobile preset uses a 4x CPU slowdown, so a task that looks harmless on a fast laptop can cross the 50 ms long-task line on a real phone.
- Baseline: the same page with every third-party script blocked.
- Method: add back one script category at a time (analytics, tag manager, chat, A/B testing, session replay, consent, ads, social embeds).
- Interactions: the taps your users actually make, such as add to cart, variant selection, menu open and accordion toggle. Repeat each sequence several times and take the median.
- Record: INP, the number of long tasks over 50 ms, and Total Blocking Time for each configuration.
Fill in a table like this for your own page:
| Configuration | INP (median of runs) | Long tasks > 50 ms | Total Blocking Time |
|---|---|---|---|
| Baseline (no third-party scripts) | your number | your number | your number |
| + analytics | your number | your number | your number |
| + tag manager | your number | your number | your number |
| + chat widget | your number | your number | your number |
| + A/B testing | your number | your number | your number |
| + session replay | your number | your number | your number |
The row where INP jumps is your first fix. Scripts also interact: each one adds tasks to the same main thread, so a tap is more likely to land behind someone else's task as the list grows.
Why Third-Party Scripts Destroy INP: The Main-Thread Contention Model
Volume is part of the problem. In our unused JavaScript study of 218 homepages, the median site loaded 77.5% of its JavaScript bytes from other domains (a count that includes a site's own CDN hostname when it differs from the main domain).
Third-party scripts hurt INP through three mechanisms:
1. Script Evaluation (Parse + Compile + Execute)
When the browser downloads a third-party JavaScript file, it must parse, compile, and execute the code on the main thread.
That cost grows with script size and is several times higher on a mid-range phone than on a developer laptop, which is why the measurement above uses throttling.
// Measure third-party script evaluation time
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.entryType === 'resource' && entry.initiatorType === 'script') {
// Scripts from third-party origins
const url = new URL(entry.name)
if (url.hostname !== location.hostname) {
console.log(`3P Script: ${url.hostname}${url.pathname}`)
console.log(` Transfer: ${entry.transferSize} bytes`)
console.log(` Duration: ${entry.duration.toFixed(0)}ms`)
}
}
}
})
observer.observe({ type: 'resource', buffered: true })2. Recurring Timer Callbacks (setInterval / requestAnimationFrame)
Many tracking scripts install recurring timers to monitor scroll position, mouse movement, or viewport visibility. Each callback takes main-thread time, and a tap that arrives while one is running has to wait for it:
// ❌ Anti-pattern: Heatmap script polling mouse position every 100ms
// This creates 10 main-thread callbacks per second
setInterval(() => {
const elements = document.elementsFromPoint(mouseX, mouseY)
recordHeatmapData(elements, Date.now())
}, 100)3. DOM Mutation and Style Recalculation
Chat widgets, consent banners, and social embeds inject DOM nodes and trigger style recalculations.
A consent management platform that injects a full-screen overlay with backdrop blur forces the browser to recalculate style and layout for the entire page. That work runs on the main thread.
// Detect DOM mutations caused by third-party scripts
const mutationObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node instanceof HTMLElement) {
const scripts = node.querySelectorAll?.('script[src]') || []
for (const script of scripts) {
const src = script.getAttribute('src') || ''
if (!src.includes(location.hostname)) {
console.warn(`3P DOM injection from: ${src}`)
console.warn(` Nodes added: ${mutation.addedNodes.length}`)
}
}
}
}
}
})
mutationObserver.observe(document.body, { childList: true, subtree: true })Attribution: Identifying Which Script Is Causing Your INP Failure
Third-party scripts usually show up as input delay: the tag is busy when the tap arrives. If you haven't confirmed which INP phase is slow yet, start with the phase-by-phase INP diagnostic workflow, then use the methods below to name the script.
Method 1: Long Animation Frames API
The older Long Tasks API only names the frame a task ran in, not the script. The Long Animation Frames API (shipped in Chrome 123) lists each script that ran for more than 5 ms inside a slow frame, with its source URL:
// Attribute slow frames to the scripts that ran in them
const loafObserver = new PerformanceObserver((list) => {
for (const frame of list.getEntries()) {
for (const script of frame.scripts) {
const host = script.sourceURL ? new URL(script.sourceURL).hostname : 'inline'
const party = host === location.hostname ? '1P' : '3P'
console.log(`${party} ${host}: ${script.duration.toFixed(0)}ms (${script.invoker}) in a ${frame.duration.toFixed(0)}ms frame`)
}
}
})
loafObserver.observe({ type: 'long-animation-frame', buffered: true })Method 2: Chrome DevTools Performance Tab
Step-by-step attribution in Chrome DevTools:
1. Open DevTools → Performance tab
2. Enable "Screenshots" and "Web Vitals" checkboxes
3. Click Record, interact with the page (click buttons, scroll, type)
4. Stop recording
5. Look for the INP marker in the Web Vitals lane
6. Click the corresponding Long Task in the Main thread flame chart
7. Expand the call stack — the bottom frame shows the responsible script URL
8. Third-party scripts appear with their CDN hostname (e.g., widget.intercom.io)Method 3: Blocking Scripts One at a Time
The most definitive attribution method is selectively blocking scripts and measuring the change. A Lighthouse navigation run doesn't interact with the page, so it can't report INP; Total Blocking Time is its lab proxy for main-thread blocking:
# Baseline, then the same run with one script domain blocked
npx lighthouse https://your-site.com \
--output=json --quiet | jq '.audits["total-blocking-time"].numericValue'
# Block Intercom and measure
npx lighthouse https://your-site.com \
--blocked-url-patterns="https://widget.intercom.io/*" \
--output=json --quiet | jq '.audits["total-blocking-time"].numericValue'
# Block Hotjar and measure
npx lighthouse https://your-site.com \
--blocked-url-patterns="https://static.hotjar.com/*" \
--output=json --quiet | jq '.audits["total-blocking-time"].numericValue'Run each several times and compare medians. Then repeat the interaction test from the measurement section with the same script blocked to confirm the INP change.
Fix Pattern 1: Defer Non-Critical Scripts Until After User Interaction
The simplest and highest-impact fix is delaying third-party script loading until the page is interactive and idle:
// ❌ Broken: All scripts load immediately, blocking INP during initial interactions
<script src="https://cdn.analytics.com/tracker.js"></script>
<script src="https://widget.chat.com/loader.js"></script>
<script src="https://cdn.heatmap.com/record.js"></script>// ✅ Fixed: Load non-critical scripts after first user interaction
function loadDeferredScripts() {
const scripts = [
'https://widget.chat.com/loader.js',
'https://cdn.heatmap.com/record.js',
]
scripts.forEach(src => {
const script = document.createElement('script')
script.src = src
script.async = true
document.body.appendChild(script)
})
}
// Trigger on first interaction OR after 5 seconds (whichever comes first)
const events = ['click', 'scroll', 'keydown', 'touchstart']
let loaded = false
function onFirstInteraction() {
if (loaded) return
loaded = true
events.forEach(e => document.removeEventListener(e, onFirstInteraction))
loadDeferredScripts()
}
events.forEach(e => document.addEventListener(e, onFirstInteraction, { once: true }))
setTimeout(onFirstInteraction, 5000) // fallback timerThis keeps third-party script evaluation from competing with the user's first interaction. Measure it the same way as above: run your interaction test before and after the change, and keep the result as your evidence.
Fix Pattern 2: Move Scripts to a Web Worker with Partytown
Partytown relocates third-party scripts from the main thread to a Web Worker, freeing the main thread for user interactions. The library intercepts DOM API calls from the worker thread and proxies them synchronously.
<!-- Install Partytown and move analytics to a Web Worker -->
<script>
// Partytown configuration (inline, before any 3P scripts)
partytown = {
forward: ['dataLayer.push', 'gtag'],
resolveUrl: (url) => {
// Proxy third-party requests through your origin to avoid CORS issues
if (url.hostname !== location.hostname) {
return new URL(`/proxy?url=${encodeURIComponent(url.href)}`, location.origin)
}
return url
}
}
</script>
<script src="/~partytown/partytown.js"></script>
<!-- Third-party scripts with type="text/partytown" run in the Worker -->
<script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXX"></script>
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXX');
</script>// Next.js integration with @builder.io/partytown
// next.config.js
const { withPartytown } = require('@builder.io/partytown/next')
module.exports = withPartytown({
partytown: {
forward: ['dataLayer.push', 'gtag'],
},
})💡 Engineering Rule of Thumb: Partytown works best for analytics, tracking, and heatmap scripts that primarily read DOM state. Scripts that require synchronous DOM writes (consent managers, A/B testing that mutates visible content) may need the main thread. Test each script individually.
Fix Pattern 3: Replace Heavy Scripts With Lightweight Alternatives
Some third-party script categories have lighter alternatives. Check the transfer size of each option in DevTools' Network panel and rerun your interaction test before you switch:
| Heavy script | Lighter option | Trade-off |
|---|---|---|
| Full analytics tag (gtag.js) | A lightweight analytics script | Fewer built-in reports |
| Live chat widget loaded on every page | The same widget loaded on click of a "Chat" button | Chat opens a moment later |
| Session-replay heatmap | Custom IntersectionObserver scroll tracking | No click maps or replays |
| Client-side tag manager with many tags | Server-side tagging | Needs a tagging server |
| jQuery kept for legacy widgets | Native DOM APIs | Rewrite effort |
Server-Side GTM: Moving Tag Work Off the Browser
Google Tag Manager's client-side container dynamically loads additional scripts based on trigger rules, so the main-thread work grows with every tag someone adds.
Server-side GTM moves tag execution to a server you control:
- Client-side flow: the browser loads the container, evaluates the triggers, then downloads and runs each vendor tag (analytics, ad pixels, conversion tracking) on the main thread.
- Server-side flow: the browser sends events to your tagging server endpoint, and that server forwards them to each vendor. Far less vendor JavaScript runs in the browser.
Fix Pattern 4: Implement a Third-Party Script Budget
Establish a measurable budget that prevents script accumulation:
// third-party-budget.ts — Enforce at build time or in CI
interface ScriptBudget {
maxThirdPartyScripts: number
maxThirdPartyBytes: number
maxMainThreadImpact: number // ms
}
const BUDGET: ScriptBudget = {
maxThirdPartyScripts: 4, // Maximum 4 third-party script domains
maxThirdPartyBytes: 150000, // 150KB total third-party JS
maxMainThreadImpact: 100, // 100ms max added main-thread time
}
// Audit function: run during CI/CD pipeline
async function auditThirdPartyBudget(pageUrl: string): Promise<void> {
const resources = await getPageResources(pageUrl) // Puppeteer or Playwright
const thirdPartyScripts = resources.filter(r =>
r.type === 'script' && !new URL(r.url).hostname.includes('your-domain.com')
)
const totalBytes = thirdPartyScripts.reduce((sum, s) => sum + s.transferSize, 0)
const uniqueDomains = new Set(thirdPartyScripts.map(s => new URL(s.url).hostname))
console.log(`Third-party scripts: ${uniqueDomains.size} domains, ${totalBytes} bytes`)
if (uniqueDomains.size > BUDGET.maxThirdPartyScripts) {
throw new Error(`BUDGET EXCEEDED: ${uniqueDomains.size} 3P domains (max: ${BUDGET.maxThirdPartyScripts})`)
}
if (totalBytes > BUDGET.maxThirdPartyBytes) {
throw new Error(`BUDGET EXCEEDED: ${totalBytes} bytes (max: ${BUDGET.maxThirdPartyBytes})`)
}
}How BugViso Surfaces the Long Tasks Behind Slow Tags
The manual method above works for one page. BugViso's performance engine collects the same lab signals during a scan:
- Core Web Vitals (LCP, CLS, FCP, TTFB, and INP on a best-effort basis) via the
web-vitalslibrary. These are lab measurements, not field data from real visitors. - Long tasks and Total Blocking Time: the count of main-thread tasks over 50 ms, the longest one, and the TBT they add up to.
- Code coverage via CDP precise JavaScript coverage, with unused bytes per file. Third-party files are labelled with their host, so a heavy vendor bundle doesn't read as your own code.
- Throttled re-loads under Slow 3G and Fast 3G profiles with 4x CPU slowdown, which show load costs that a fast office connection hides.
- Console errors and failed requests, including third-party scripts that fail to load or throw at runtime.
It doesn't attribute each long task to a script; use the Long Animation Frames snippet above for that.
For the full list of what BugViso tests here, see the Core Web Vitals audit.
Frequently Asked Questions
Will deferring analytics scripts cause data loss?
Deferring by 5 seconds (or until first interaction) loses the visitors who leave before the trigger fires without interacting.
How many that is depends on your traffic, so check it: compare session counts for a week before and after the change.
Keep the analytics tag that measures page views on the early path if you need every bounce counted, and defer the heavier tags.
Does Partytown work with Google Tag Manager?
Yes, but with limitations. Partytown moves GTM's container script to a Web Worker, which eliminates main-thread blocking.
However, tags within GTM that require synchronous DOM manipulation (e.g., A/B testing scripts that change visible content) may not function correctly in the Worker context. Test each tag individually.
Can I detect third-party script impact from CrUX data alone?
No. CrUX reports aggregate INP scores but doesn't attribute them to specific scripts. You need lab testing (DevTools Performance tab, Lighthouse with --blocked-url-patterns) or a Real User Monitoring (RUM) tool with Long Task attribution to identify individual script responsibility.
What's the maximum number of third-party scripts a page can handle and still pass INP?
There's no fixed number. One script that runs heavy work on every click can fail INP on its own, while several small, deferred tags may not matter.
Use the 200 ms threshold as the budget, measure each script with the blocking test, and stop adding tags once the measured INP gets close to it.
How do I convince marketing to remove a third-party script?
Present the measured delta from your own page: "With this chat widget, INP on the product page is N ms; without it, M ms.
That's the difference between passing and failing Google's 200 ms threshold." A before/after number from your own site is more persuasive than general advice. A BugViso audit adds the per-page long-task, TBT and coverage data to that case.
Written by
Kazi Khalid Hasan Tamim · BugViso Team
Kazi writes BugViso’s guides on website audits, Core Web Vitals, technical SEO, accessibility and AI search. The data in them comes from audits BugViso runs in a real Chromium browser, including our 219-site study of website health.
Summarise with AI
Open this guide in your assistant.
Follow BugViso
New guides and audit data as we publish them.
AI visibility tracker
Is your brand in AI answers?
See how often AI assistants mention you, cite your site and rank you against your competitors.
- ChatGPT
- Gemini
- Perplexity
- Claude
- AI Overviews
See where your site stands
Run a free BugViso audit for SEO, speed, accessibility and AI search readiness — with fixes you can ship today.