Open data & tools

Measure real-user Core Web Vitals on ad pages with the open-source web-vitals library

Last updated Published By the editorial team6 min4 sources

Key takeaways

  • web-vitals is Google's open-source (Apache-2.0) JavaScript library for measuring Core Web Vitals on real users, in a way that matches how Chrome reports them to CrUX, PageSpeed Insights and Search Console.
  • Version 6, released in July 2026, added soft navigation reporting for browsers that support it; 6.2.3 was the latest npm release in November 2026.
  • onLCP and onINP work in Chromium, Firefox and Safari, while onCLS is supported only in Chromium browsers according to the library's documentation.
  • The attribution build adds diagnostic fields such as largestShiftTarget for CLS and interactionTarget for INP, which show whether an ad container causes the problem.
  • The library cannot see inside iframes, so pages with ads in iframes may show different values than CrUX, which does include iframe content.
Firefox web browser displaying a Wikipedia page
Image: Firefox web browser on wikipedia page,Mozilla Corporation,CC BY-SA 4.0,via Wikimedia Commons.

The web-vitals library is Google’s open-source JavaScript package for measuring Largest Contentful Paint (LCP), Interaction to Next Paint (INP) and Cumulative Layout Shift (CLS) on real visitors. Add it to your pages, send each metric to an endpoint you control, and you get field data for every browser and page, not just the popular origins CrUX covers. Its attribution build tells you which element, often an ad slot, caused a shift or a slow interaction.

Why measure your own field data when CrUX exists?

CrUX is free but limited: only sufficiently popular, publicly discoverable pages, only eligible Chrome users, 28-day windows. Your own real-user monitoring (RUM) adds:

  • Every page template, including low-traffic articles where ad layouts differ.
  • Firefox and Safari visitors for LCP and INP.
  • Attribution: the CSS selector of the element behind the metric.
  • Immediate feedback: you see the effect of an ad layout change the next day, not after 28 days.

What the library measures, and where

According to the README, the library is about 3K (brotli) and matches how Chrome reports metrics to CrUX, PageSpeed Insights and Search Console. It measures the three Core Web Vitals (CLS, INP, LCP) plus First Contentful Paint (FCP) and Time to First Byte (TTFB).

Browser support listed in the README:

Function Browsers
onCLS() Chromium
onINP() Chromium, Firefox, Safari
onLCP() Chromium, Firefox, Safari
onFCP(), onTTFB() Chromium, Firefox, Safari
Soft navigations Chromium 151+

The library’s thresholds are exported as constants: LCPThresholds is [2500, 4000], INPThresholds is [200, 500] and CLSThresholds is [0.1, 0.25] (good up to the first value, poor from the second). Each metric object also carries a ready-made rating of good, needs-improvement or poor.

Version 6 in brief

The changelog dates v6.0.0 to July 21, 2026, adding soft navigation support. The upgrade guide lists the breaking changes: types are exported as explicit types (use import type), requestIdleCallback is capped at one second, and in the attribution build onINP() no longer includes processed event entries unless you set includeProcessedEventEntries: true. The latest release on npm in November 2026 was 6.2.3 (October 5, 2026).

Step 1: install and load

With a bundler:

npm install web-vitals
import { onCLS, onINP, onLCP } from 'web-vitals/attribution';

Without a bundler, self-host the built file from the package (dist/web-vitals.attribution.iife.js). The README shows CDN examples but notes that unpkg, jsDelivr and cdnjs are not affiliated with Google and that self-hosting is better for security, reliability and performance. The README’s CDN examples still point to web-vitals@5; if you copy them, pin the major version you actually tested.

Step 2: send each metric to your endpoint

This snippet uses the attribution build so every beacon carries the element behind the metric:

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

function send(metric) {
  const a = metric.attribution || {};
  const target =
    metric.name === 'CLS' ? a.largestShiftTarget :
    metric.name === 'INP' ? a.interactionTarget :
    metric.name === 'LCP' ? a.target : undefined;

  const body = JSON.stringify({
    name: metric.name,
    value: metric.value,
    rating: metric.rating,
    id: metric.id,
    nav: metric.navigationType,
    page: new URL(metric.navigationURL || location.href).pathname,
    target,
  });
  navigator.sendBeacon('/rum', body);
}

onCLS(send);
onINP(send);
onLCP(send);

Notes drawn from the README:

  • navigator.sendBeacon() is used because it can send while the page is unloading.
  • navigationURL gives the URL the metric belongs to, which matters with soft navigations; it is optional on the metric object, hence the location.href fallback.
  • Use id to group values for the same page view; after a back/forward cache restore the library creates a new metric with a new id.
  • Do not call onCLS() and friends repeatedly on the same page; each call creates observers for the page’s lifetime.

Step 3: store and summarise the data

Any endpoint that accepts a POST works: your analytics tool’s custom events, a serverless function or a few lines of Node. This minimal receiver appends each beacon to a file:

// rum-server.mjs: append each beacon as one JSON line
import { createServer } from 'node:http';
import { appendFile } from 'node:fs/promises';

createServer(async (req, res) => {
  if (req.method === 'POST' && req.url === '/rum') {
    let body = '';
    for await (const chunk of req) body += chunk;
    if (body.length < 5000) {
      await appendFile('rum.ndjson', JSON.stringify({ t: Date.now(), ...JSON.parse(body) }) + '\n');
    }
    res.writeHead(204).end();
  } else {
    res.writeHead(404).end();
  }
}).listen(8787);

And the 75th percentile per metric:

// summarize.mjs: p75 per metric from rum.ndjson
import { readFileSync } from 'node:fs';
const rows = readFileSync('rum.ndjson', 'utf8').trim().split('\n').map(JSON.parse);
const by = {};
for (const r of rows) (by[r.name] ??= []).push(r.value);
for (const [name, v] of Object.entries(by)) {
  v.sort((a, b) => a - b);
  const p75 = v[Math.ceil(v.length * 0.75) - 1];
  console.log(name, 'n=' + v.length, 'p75=' + p75);
}

We ran both scripts locally with a test beacon. In production, put the receiver behind your web server, validate input more strictly and rotate the file. If you already run Matomo, Plausible or Umami, sending metrics as custom events avoids a separate store (see open-source analytics next to AdSense).

Keep the volume under control

On a busy site you do not need a beacon from every page view. Decide once per page load whether to report, so all metrics from one view are either kept or dropped together:

const SAMPLE_RATE = 0.1; // report about 10% of page views
const sampled = Math.random() < SAMPLE_RATE;
if (sampled) {
  onCLS(send);
  onINP(send);
  onLCP(send);
}

Store the sample rate with the data if you change it later, so counts stay comparable. Percentiles do not need correction for sampling, but totals do. For low-traffic templates, raise the rate or report everything: a p75 computed from a few dozen values per month is not stable enough to judge an ad layout change.

How do I find out whether ads cause my CLS?

Group CLS beacons by target and look at the poor ones:

  1. Filter rows where name is CLS and rating is poor.
  2. Count the target values. Selectors containing adsbygoogle, your ad wrapper class, or the element right below an ad slot point to unreserved ad space.
  3. Compare by page template. If only article pages with in-content units are affected, the fix is in that template.

The largestShiftTarget is the element that moved the most, not always the ad itself. A paragraph pushed down by an ad that expanded above it is the typical pattern. The fix is to reserve the slot’s height in CSS, described in preventing CLS from ads.

For INP, a selector pointing to your menu or a button means the main thread was busy when the visitor interacted. If that coincides with ad script execution, the Lighthouse ads-on vs ads-off comparison helps confirm it in the lab.

Limitations to keep in mind

  • No visibility into iframes. The README states that the underlying APIs cannot see <iframe> content, even same-origin, while CrUX does include it. Shifts inside an ad iframe are invisible to you.
  • CLS is Chromium-only. Safari and Firefox visitors contribute LCP and INP but no CLS.
  • Sampling bias. Beacons can be lost when tabs are killed. Do not expect a 1:1 match with pageviews.
  • Soft navigations. Single-page apps need v6 and a Chromium version that supports the feature for per-route metrics.

Common mistakes

  • Loading the library from a public CDN without a pinned version, then silently upgrading to a major version with breaking changes.
  • Averaging values. Core Web Vitals are assessed at the 75th percentile; averages hide the tail where ads hurt.
  • Sending full URLs with query strings that may contain personal data. Send the path only.
  • Treating the attribution target as proof of blame. It shows where the symptom appeared; confirm the cause before removing an ad unit.

Open-source tools mentioned

ToolLicence
web-vitalsApache-2.0

Frequently asked questions

Does the web-vitals library slow down my page?

The README describes it as a tiny library of about 3K brotli-compressed, with the attribution build about 1.5K larger. It uses buffered PerformanceObserver entries, so it does not need to load early; the documentation recommends deferring it until other user-impacting code has loaded. Call each onXXX function once per page load to avoid extra observers.

Why do my web-vitals numbers differ from CrUX?

CrUX covers only eligible Chrome users and aggregates 28 days at the 75th percentile, while your data covers every browser you measure. The library also cannot see inside iframes, and ads usually render in iframes, whereas CrUX includes iframe content. Compare p75 values for Chrome visitors only before concluding that one source is wrong.

Can I send web-vitals data to Google Analytics 4?

Yes. The README includes a gtag example that sends each metric as an event with metric_id, delta and a debug_target taken from the attribution build. It notes that Google Analytics does not show metric distributions in built-in reports, so you build them from the Data API or the BigQuery export. Self-hosting the data is an alternative if you prefer not to.

Do I need consent to collect Core Web Vitals?

It depends on what you collect, where your visitors are and how you identify them. Performance timings sent without cookies or identifiers are different from tracking, but the rules vary by jurisdiction and this guide is not legal advice. Keep payloads minimal (metric, value, page path, rating, target selector) and check your consent setup with your CMP and counsel.

Sources

  1. web-vitals README · GoogleChrome on GitHub
  2. web-vitals CHANGELOG · GoogleChrome on GitHub
  3. Upgrading to v6 · GoogleChrome on GitHub
  4. web-vitals latest version (npm registry) · npm