Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

Your chat widget is why the Add to cart button feels slow: third-party scripts and INP

A client asks why their store "feels laggy" on phones. The page loads fast and Lighthouse is mostly green. Yet a tap on Add to cart takes a visible moment before anything happens. In our experience it is often not the s

A client asks why their store "feels laggy" on phones. The page loads fast and Lighthouse is mostly green. Yet a tap on Add to cart takes a visible moment before anything happens.

In our experience it is often not the store's own code. It is the stack of scripts added over the years: a chat widget, a session-replay tool, two pixels, a review badge, a tag manager that loads five more tags. Each one is "only 30 KB". Together they keep the main thread busy exactly when the user taps.

That delay is what Interaction to Next Paint (INP) measures. INP replaced FID as a Core Web Vital in March 2024. It is the time from a tap, click or key press to the next frame the user sees. 200 ms or less is good, above 500 ms is poor. Unlike FID, it counts the whole interaction, not just the first one, and not just the input delay.

Here is how we find which scripts are to blame and what we do about them.

Why third-party code hurts INP specifically

An interaction has three parts:

  1. Input delay: the main thread is busy with something else when the tap arrives.
  2. Processing: your event handlers (and everyone else's) run.
  3. Presentation delay: the browser recalculates styles, lays out and paints.

Third-party scripts hit the first two:

  • Input delay. A widget that wakes up on a timer, a replay tool that serializes the DOM, or a tag that fires on scroll can be in the middle of a long task when the user taps. The tap waits.
  • Processing. Many tools add their own click, pointerdown or input listeners to the whole document. Session replay and heatmap tools do this by design. Those listeners run on every interaction, before the browser can paint your response.
  • The dataLayer.push trap. When your click handler pushes an event to Google Tag Manager, tags triggered by that event can run their code right there, inside your handler. A "simple" add-to-cart event can turn into several vendors' scripts running before the cart icon updates.

Step 1: find the culprits with Long Animation Frames

The Long Animation Frames API (LoAF, available in Chromium since version 123) tells you not only that a frame was slow but which scripts ran during it, with their source URL. Paste this into the console, then use the page normally:

new PerformanceObserver((list) => {
  for (const frame of list.getEntries()) {
    if (frame.duration < 100) continue;
    console.group(`Long frame: ${Math.round(frame.duration)} ms`);
    for (const s of frame.scripts) {
      console.log(
        `${Math.round(s.duration)} ms`,
        s.invokerType,          // e.g. event-listener, user-callback, classic-script
        s.invoker,              // e.g. DOCUMENT.onclick, TimerHandler:setTimeout
        s.sourceURL || '(inline)',
        s.sourceFunctionName
      );
    }
    console.groupEnd();
  }
}).observe({ type: 'long-animation-frame', buffered: true });

Tap the buttons that matter: add to cart, open the menu, apply a filter, type in search. If most of the slow frames list sourceURLs from other domains, you have your answer.

Step 2: measure it on real users, not on your laptop

Your MacBook will not reproduce what a mid-range Android phone does. The web-vitals library (v4+) exposes the same LoAF data for the actual INP interaction of real visitors:

import { onINP } from 'web-vitals/attribution';

onINP(({ value, attribution }) => {
  const scripts = attribution.longAnimationFrameEntries
    .flatMap((frame) => frame.scripts)
    .sort((a, b) => b.duration - a.duration)
    .slice(0, 3)
    .map((s) => ({
      url: s.sourceURL,
      fn: s.sourceFunctionName,
      ms: Math.round(s.duration),
    }));

  navigator.sendBeacon('/vitals', JSON.stringify({
    inp: Math.round(value),
    target: attribution.interactionTarget,   // CSS selector of the element
    inputDelay: Math.round(attribution.inputDelay),
    processing: Math.round(attribution.processingDuration),
    presentation: Math.round(attribution.presentationDelay),
    scripts,
  }));
});

After a week you will have a list like "INP on button.add-to-cart, mostly processing time, top script: widget.vendor.com/chat.js". That is a conversation you can have with the business: this tool costs you X ms on the most important button.

Step 3: fixes, from cheapest to most work

Remove what nobody uses

Most audits we do find at least one script for a tool the client stopped paying for, a pixel for an ad account that is closed, or two analytics tools doing the same job. Removing it is free and has no trade-offs. Start with the tag manager: list every tag and ask who looks at its data.

Load the chat widget on demand (a facade)

A chat widget does not need to exist until someone wants to chat. Show a lightweight button that looks like the widget launcher and load the real script on the first click:

<button class="chat-facade" type="button" aria-label="Open chat">💬</button>
const facade = document.querySelector('.chat-facade');

function loadScript(src) {
  return new Promise((resolve, reject) => {
    const s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

facade.addEventListener('click', async () => {
  facade.disabled = true;
  await loadScript('https://widget.example.com/chat.js'); // your vendor's script
  facade.remove();
  // Then open the chat with your vendor's JS API (most widgets have an "open" method).
}, { once: true });

The first click on the chat is a little slower. Every other interaction on every page is faster. That is a good trade.

Give the user feedback first, then let the tags run

In your own handlers, update the UI, yield to the browser so it can paint, and only then do the analytics work:

function yieldToMain() {
  if (globalThis.scheduler?.yield) return scheduler.yield();
  return new Promise((resolve) => setTimeout(resolve, 0));
}

addToCartButton.addEventListener('click', async () => {
  cart.add(product);          // your logic
  renderCartBadge();          // visible feedback

  await yieldToMain();        // the browser can paint the badge now

  window.dataLayer.push({ event: 'add_to_cart', /* ... */ });
});

scheduler.yield() is available in Chromium (129+); the setTimeout fallback works everywhere. The user sees the result immediately and the tags still fire a few milliseconds later.

Delay non-critical scripts until the page is idle

Review badges, recommendation widgets below the fold and social embeds can wait (loadScript is the helper from the facade example):

function whenIdle(fn, timeout = 4000) {
  if ('requestIdleCallback' in window) {
    requestIdleCallback(fn, { timeout });
  } else {
    setTimeout(fn, 2000);
  }
}

whenIdle(() => loadScript('https://reviews.example.com/badge.js'));

Be honest about the trade-off: anything you delay will miss visitors who leave in the first seconds. That is fine for a review badge. It may not be fine for the analytics tag you use to measure ad campaigns, so decide tag by tag.

Move scripts off the main thread (with care)

Tools like Partytown run third-party scripts in a web worker. It can work well for simple pixels, but scripts that need synchronous DOM access may break or behave differently. Test each one, and do not start here: the steps above are usually enough.

What to bring to the business side

Developers rarely get to remove a marketing tool on their own. What works for us is a short table: the script, what it does, who uses its data, and how many milliseconds it adds to key interactions according to real-user data. Most decisions make themselves once the cost is visible next to the value.

If your store feels slow on taps even though the page loads fast, start with the LoAF snippet above. Ten minutes in the console usually tells you whose code you are waiting for.

We are a web studio working on e-commerce performance; more on how we approach it here.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.