| | |

Playwright 28 ๐ŸŽญ Performance โ€” page.metrics() and Core Web Vitals measurement

โฑ๏ธ Estimated read: 20 min | |

A Playwright test that finishes in milliseconds has proved nothing about how the page felt to the user who paid for it. The navigation may have taken three seconds on a 4G phone, the hero image may have pushed every other element down as it loaded, and the checkout button may have frozen for half a second on the first tap. None of those facts appear in a green checkmark. Performance measurement is the practice of turning a green checkmark into a number with a threshold attached.

Playwright does not expose a page.metrics() method the way Puppeteer does. What Playwright offers instead are three complementary measurement paths that, taken together, cover the same ground: the Chrome DevTools Protocol Performance domain for Chromium-only counters like LayoutDuration, ScriptDuration, and JSHeapUsedSize; the browser’s own performance API for the Navigation and Resource Timing waterfalls, available in every engine; and a PerformanceObserver installed before navigation that captures the five Core Web Vitals โ€” LCP, INP, CLS, FCP, and TTFB โ€” as the page produces them.

This chapter walks through the three paths in that order, then pulls them together into a reliable measurement harness. The earlier sections cover the CDP session and the delta arithmetic that converts the domain’s cumulative counters into a per-window number, and the PerformanceObserver script that captures the vitals without bundling an extra dependency. The later sections cover the Navigation Timing breakdown, the Resource Timing waterfall, and the warm-up, throttle, and median steps that turn a single noisy number into an assertion a CI gate can trust.

Key point: Playwright measures performance three ways โ€” CDP Performance.getMetrics for Chromium’s cumulative counters, performance.getEntriesByType('navigation' | 'resource') for the waterfall, and a buffered PerformanceObserver for the Core Web Vitals โ€” and the numbers are only meaningful once a warm-up run is discarded, the network and CPU are throttled to the target device, and the median of several runs replaces the first result.


Why performance measurement exists

The “fast on my machine” problem. A test that waits for networkidle and asserts on a selector passes on a laptop with a warm cache and a fiber connection. The same test on the CI runner, on a 4G emulation, against a cold cache, may pass too โ€” because the assertion does not mention time. The user’s experience is time, and a test that ignores time is testing something the user does not experience.

The page.metrics() question. Puppeteer ships page.metrics(), a convenience that returns a fixed object of counters โ€” LayoutDuration, RecalcStyleDuration, ScriptDuration, TaskDuration, JSHeapUsedSize, and a handful of counts โ€” from the Chrome DevTools Protocol. Playwright does not bundle that method. The equivalent is two lines: context.newCDPSession(page) returns a session, and client.send('Performance.getMetrics') returns the same counters as an array of { name, value } pairs. Everything the Puppeteer method does is reachable; it is just spelled out.

The lab-versus-field distinction. Field data โ€” the numbers Google reports in Search Console โ€” is collected from real users on real devices, and it is the number that matters for a ranking decision. Lab data is what a test can produce, on a schedule, deterministically, before the change ships. The two are not the same and never will be. But a lab measurement that uses the same metric definitions as the field โ€” LCP as the last large element paint, CLS as the sum of unexpected shifts โ€” is a leading indicator of the field number, and it is the only one available in CI.

The definition problem. “Fast” is not a metric. Largest Contentful Paint, Interaction to Next Paint, and Cumulative Layout Shift are metrics with published thresholds and documented algorithms. A test that asserts “the page loaded in under two seconds” is measuring an arbitrary boundary. A test that asserts “LCP is 2500 ms or less” is measuring the exact signal Google uses, and the threshold is not up for debate.

The single-run noise problem. One measurement on one machine is a sample of size one. The first run pays for cold caches, JIT warm-up, uncompiled stylesheets, and DNS. The second run does not. A test that measures the first run and asserts on it will be flaky for reasons that have nothing to do with a regression, and a suite that is flaky gets muted, and a muted suite gets deleted. The discipline that makes performance assertions survivable is warm-up, repetition, and median.

The trade-off. A performance suite is slower than a functional one โ€” every measurement is at least a full navigation, and a median of five runs is five navigations. It is also more brittle, because it depends on the machine, the network emulation, and the browser version. It repays that cost only when the assertions are attached to budgets that the team agreed to, and only when the numbers are stable enough that a red run means a regression rather than a slow CI pod.


a. The CDP Performance domain and the delta arithmetic

The CDP session is created from the browser context, not from the page. The Performance domain is disabled by default, and Performance.enable is what makes getMetrics return anything useful.

// tests/metrics.spec.ts
import { test } from '@playwright/test';

test('collect CDP performance counters', async ({ page, context, browserName }) => {
  test.skip(browserName !== 'chromium', 'CDP is Chromium-only');

  // a CDP session is opened from the context, against a specific page
  const client = await context.newCDPSession(page);

  // enable the domain; without this the metrics array is empty
  await client.send('Performance.enable');

  await page.goto('/dashboard');

  // returns { metrics: Array<{ name: string, value: number }> }
  const { metrics } = await client.send('Performance.getMetrics');
  console.log(metrics.find((m) => m.name === 'ScriptDuration'));
});

The metrics are cumulative since the domain was enabled, not per action. That distinction is the entire reason the delta pattern exists: call getMetrics once before an action and once after, and subtract the two values to get the cost of the action alone.

// the helper that turns cumulative counters into a per-window delta
async function measureWindow(client, action) {
  const before = await client.send('Performance.getMetrics');
  await action();
  const after = await client.send('Performance.getMetrics');

  const map = (m) => Object.fromEntries(m.metrics.map((k) => [k.name, k.value]));
  const b = map(before);
  const a = map(after);

  return {
    // durations are already in seconds
    layoutDuration: a.LayoutDuration - b.LayoutDuration,
    recalcStyleDuration: a.RecalcStyleDuration - b.RecalcStyleDuration,
    scriptDuration: a.ScriptDuration - b.ScriptDuration,
    taskDuration: a.TaskDuration - b.TaskDuration,
    // gauges, not counters; subtract to see the growth
    heapUsed: a.JSHeapUsedSize - b.JSHeapUsedSize,
    nodes: a.Nodes - b.Nodes,
  };
}

The gauge-versus-counter difference matters when reading the output. LayoutDuration, ScriptDuration, and TaskDuration are counters that only ever grow, so a subtraction yields the cost of the window. JSHeapUsedSize and Nodes are gauges that go up and down with garbage collection, so a subtraction can be negative, and a large positive delta across a repeated interaction is the signal that something is leaking.

The domain is Chromium-only, and it is a low-overhead source of truth about what the main thread was doing. When a Web Vitals number looks bad, the CDP counters say whether the time went into layout, into style recalculation, or into JavaScript โ€” three different bugs with three different fixes.


b. Web Vitals via a buffered PerformanceObserver

The addInitScript runs before any page script, so a PerformanceObserver registered there catches entries that would otherwise be gone by the time the test’s page.evaluate runs. That is what the buffered: true flag does on each observe call: it replays the entries the browser collected before the observer existed.

// install the observer before navigating
await page.addInitScript(() => {
  window.__vitals = { LCP: 0, CLS: 0, INP: 0, FCP: 0, TTFB: 0 };

  // Largest Contentful Paint: keep the newest entry, not the largest
  new PerformanceObserver((list) => {
    const entries = list.getEntries();
    window.__vitals.LCP = entries[entries.length - 1].startTime;
  }).observe({ type: 'largest-contentful-paint', buffered: true });

  // Cumulative Layout Shift: skip shifts caused by user input
  new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
      if (!entry.hadRecentInput) window.__vitals.CLS += entry.value;
    }
  }).observe({ type: 'layout-shift', buffered: true });

  // Interaction to Next Paint: track the longest event duration
  new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
      if (entry.duration > window.__vitals.INP) window.__vitals.INP = entry.duration;
    }
  }).observe({ type: 'event', buffered: true, durationThreshold: 16 });

  // First Contentful Paint from the paint timeline
  new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
      if (entry.name === 'first-contentful-paint') window.__vitals.FCP = entry.startTime;
    }
  }).observe({ type: 'paint', buffered: true });
});

Three details are easy to get wrong. LCP keeps the newest entry, not the largest one โ€” the browser reports a new candidate every time a larger element paints, and the last one wins. CLS is a sum, not a max, and the hadRecentInput filter is what excludes shifts the user caused by clicking. INP needs durationThreshold: 16 because the default observer drops entries shorter than 16 ms, which is fine for reporting slow interactions but wrong for a test that wants the candidate set to be complete.

The TTFB number comes from the Navigation Timing entry, not from a PerformanceObserver:

// read the vitals after the page has settled
const [nav] = await page.evaluate(() =>
  performance.getEntriesByType('navigation').map((n) => ({
    // TTFB is the gap between request start and first byte
    ttfb: n.responseStart - n.requestStart,
    dcl: n.domContentLoadedEventEnd,
    load: n.loadEventEnd,
  }))
);

const vitals = await page.evaluate(() => ({
  ...window.__vitals,
  TTFB: nav.ttfb,
}));

The web-vitals library from Google wraps this same set of observers behind a stable API โ€” onLCP, onINP, onCLS, onFCP, onTTFB โ€” and adds the rating thresholds and attribution. It is worth adopting when the project already bundles it into the app, because the test can then read from a single window.__webVitals object the app populates itself, and the metric definitions stay in lockstep with the app’s own reporting.

// if the app ships web-vitals, expose the values for the test to read
await page.addInitScript(() => {
  window.__webVitals = {};
  window.__reportVital = (metric) => {
    window.__webVitals[metric.name] = metric.value;
  };
});
// the app calls window.__reportVital({ name: 'LCP', value: 1820, ... })

c. Navigation Timing and Resource Timing

The Navigation Timing entry is the full waterfall for the document itself. Every offset is milliseconds from navigationStart, which is effectively zero, so the fields can be read as absolute timestamps as well as durations.

// the raw waterfall for the document
const nav = await page.evaluate(() => {
  const [n] = performance.getEntriesByType('navigation');
  return {
    dns: n.domainLookupEnd - n.domainLookupStart,
    tcp: n.connectEnd - n.connectStart,
    tls: n.secureConnectionStart ? n.connectEnd - n.secureConnectionStart : 0,
    ttfb: n.responseStart - n.requestStart,
    download: n.responseEnd - n.responseStart,
    domInteractive: n.domInteractive,
    domContentLoaded: n.domContentLoadedEventEnd,
    load: n.loadEventEnd,
    transferSize: n.transferSize,
  };
});

The Resource Timing entries are the same shape per subresource, and they are the fastest way to find the one asset that is eating the load time. Filter by initiatorType, sort by duration, and read the top five:

// the slowest subresources in the page
const slowest = await page.evaluate(() => {
  return performance
    .getEntriesByType('resource')
    .map((r) => ({
      name: r.name,
      type: r.initiatorType,   // 'script', 'img', 'fetch', ...
      duration: r.duration,    // start to last byte, in ms
      transferSize: r.transferSize, // wire bytes, including headers
    }))
    .sort((a, b) => b.duration - a.duration)
    .slice(0, 5);
});

A cross-origin resource only exposes transferSize and the detailed timings when the server sends Timing-Allow-Origin. Without it, the entry is present but the size is 0 and the sub-timings collapse to 0. The tests that read third-party resources should expect this and not assert on a field the browser zeroed out.

The combined waterfall is what the resource entries are for: the document load stops at load, and every resource that finished before that mark contributed to the number the user waited for. The trace viewer’s Network tab shows the same data graphically, but the programmatic form is what a CI assertion can read.


d. Reliable measurement: warm-up, throttle, and median

A single navigation is not a measurement. The pattern that survives is a warm-up run whose values are discarded, N measured runs against identical conditions, and a median โ€” not a mean, because the mean is dragged up by a single cold run and a flaky assertion is a deleted test.

// warm-up and median over several identical runs
async function measureMedian(page, url, runs = 5) {
  const samples: number[] = [];

  // run 0 exists only to warm the JIT, the CSS cache, and DNS
  await page.goto(url);
  await page.waitForLoadState('networkidle');

  for (let i = 0; i < runs; i++) {
    await page.goto('about:blank');               // reset the document
    const start = Date.now();
    await page.goto(url, { waitUntil: 'load' });
    samples.push(Date.now() - start);
  }

  // sort and take the middle value; even counts average the two middles
  samples.sort((a, b) => a - b);
  return samples[Math.floor(samples.length / 2)];
}

Conditional determinism is the other half. The device under test is a mid-range phone on a slow network, and unless the throttle emulates that, the test measures the CI pod’s fiber. Playwright’s devices presets cover some of this; the CDP Network.emulateNetworkConditions and Emulation.setCPUThrottlingRate calls cover the rest and are the ones that match the values a Lighthouse run would use.

// emulate a slow 4G phone before the first navigation
const client = await context.newCDPSession(page);

await client.send('Network.emulateNetworkConditions', {
  offline: false,
  latency: 150,                                        // RTT in ms
  downloadThroughput: (1.6 * 1024 * 1024) / 8,          // 1.6 Mbps in bytes/s
  uploadThroughput: (750 * 1024) / 8,                   // 750 kbps in bytes/s
});

// 4x CPU slowdown approximates a mid-range Android device
await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });

The final piece is isolation. A performance test that runs in the same worker as ten functional tests inherits their memory pressure and their cache warmth. The test.describe.configure({ mode: 'serial' }) keeps a measurement block together, and the test.use({ trace: 'off' }) turns the trace recorder off, because snapshotting the DOM mid-navigation is one of the more expensive things a test can do and it pollutes the measurement.

The budgets themselves belong in a config file, not in the test body, so they can be revised once per quarter without touching the code:

// tests/perf-budget.ts
export const BUDGET = {
  LCP: 2500,   // good โ‰ค 2.5s
  INP: 200,    // good โ‰ค 200ms
  CLS: 0.1,    // good โ‰ค 0.1
  FCP: 1800,   // good โ‰ค 1.8s
  TTFB: 800,   // good โ‰ค 800ms
};

Complete Example Session

// ============================================
// PART 1: THE SESSION AND THE DOMAIN
// ============================================
// tests/perf.spec.ts
import { test, expect } from '@playwright/test';

test('measures LCP, INP, CLS, FCP, TTFB', async ({ page, context, browserName }) => {
  test.skip(browserName !== 'chromium', 'CDP is Chromium-only');
  const client = await context.newCDPSession(page);
  await client.send('Performance.enable');
  await client.send('Network.enable');

  // ============================================
  // PART 2: THE THROTTLE
  // ============================================
  await client.send('Network.emulateNetworkConditions', {
    offline: false,
    latency: 150,
    downloadThroughput: (1.6 * 1024 * 1024) / 8,
    uploadThroughput: (750 * 1024) / 8,
  });
  await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });

  // ============================================
  // PART 3: THE OBSERVER
  // ============================================
  await page.addInitScript(() => {
    window.__vitals = { LCP: 0, CLS: 0, INP: 0, FCP: 0 };

    new PerformanceObserver((list) => {
      const e = list.getEntries();
      window.__vitals.LCP = e[e.length - 1].startTime;
    }).observe({ type: 'largest-contentful-paint', buffered: true });

    new PerformanceObserver((list) => {
      for (const e of list.getEntries()) {
        if (!e.hadRecentInput) window.__vitals.CLS += e.value;
      }
    }).observe({ type: 'layout-shift', buffered: true });

    new PerformanceObserver((list) => {
      for (const e of list.getEntries()) {
        if (e.duration > window.__vitals.INP) window.__vitals.INP = e.duration;
      }
    }).observe({ type: 'event', buffered: true, durationThreshold: 16 });

    new PerformanceObserver((list) => {
      for (const e of list.getEntries()) {
        if (e.name === 'first-contentful-paint') window.__vitals.FCP = e.startTime;
      }
    }).observe({ type: 'paint', buffered: true });
  });

  // ============================================
  // PART 4: THE WARM-UP RUN
  // ============================================
  await page.goto('/');
  await page.waitForLoadState('networkidle');

  // ============================================
  // PART 5: THE MEASURED RUN
  // ============================================
  const before = await client.send('Performance.getMetrics');
  await page.reload({ waitUntil: 'load' });
  const after = await client.send('Performance.getMetrics');

  // ============================================
  // PART 6: THE CDP DELTA
  // ============================================
  const map = (m: { metrics: { name: string; value: number }[] }) =>
    Object.fromEntries(m.metrics.map((k) => [k.name, k.value]));
  const b = map(before);
  const a = map(after);

  const cdp = {
    layoutDuration: a.LayoutDuration - b.LayoutDuration,
    scriptDuration: a.ScriptDuration - b.ScriptDuration,
    taskDuration: a.TaskDuration - b.TaskDuration,
    heapGrowth: a.JSHeapUsedSize - b.JSHeapUsedSize,
  };

  // ============================================
  // PART 7: THE VITALS
  // ============================================
  const [nav] = await page.evaluate(() =>
    performance.getEntriesByType('navigation').map((n) => ({
      ttfb: n.responseStart - n.requestStart,
      load: n.loadEventEnd,
    }))
  );

  const vitals = await page.evaluate(() => ({
    ...window.__vitals,
  }));
  vitals.TTFB = nav.ttfb;

  // ============================================
  // PART 8: THE WATERFALL
  // ============================================
  const slowest = await page.evaluate(() =>
    performance
      .getEntriesByType('resource')
      .map((r) => ({
        name: r.name.split('/').pop(),
        type: r.initiatorType,
        duration: Math.round(r.duration),
      }))
      .sort((x, y) => y.duration - x.duration)
      .slice(0, 5)
  );

  // ============================================
  // PART 9: THE BUDGETS
  // ============================================
  const BUDGET = { LCP: 2500, INP: 200, CLS: 0.1, FCP: 1800, TTFB: 800 };

  // ============================================
  // PART 10: THE ASSERTIONS
  // ============================================
  expect(vitals.LCP).toBeLessThanOrEqual(BUDGET.LCP);
  expect(vitals.FCP).toBeLessThanOrEqual(BUDGET.FCP);
  expect(vitals.CLS).toBeLessThanOrEqual(BUDGET.CLS);
  expect(vitals.TTFB).toBeLessThanOrEqual(BUDGET.TTFB);
  // INP is only meaningful after an interaction; assert on the tracked candidate
  expect(vitals.INP).toBeLessThanOrEqual(BUDGET.INP);

  console.log({ vitals, cdp, slowest });
});

The ten parts covered the CDP session, the network and CPU throttle that emulate a mid-range phone, the buffered PerformanceObserver, the warm-up run, the measured reload, the CDP delta arithmetic, the vitals evaluation, the resource waterfall, the budget constants, and the assertions.


Quick Reference

The three measurement paths

PathEngineReads
CDP Performance.getMetricsChromiumLayout, script, task, heap
performance.getEntriesByTypeAllNavigation and resource timing
PerformanceObserverAllLCP, INP, CLS, FCP

Core Web Vitals thresholds

MetricGoodNeeds improvementPoor
LCPโ‰ค 2.5 s2.5 โ€“ 4.0 s> 4.0 s
INPโ‰ค 200 ms200 โ€“ 500 ms> 500 ms
CLSโ‰ค 0.10.1 โ€“ 0.25> 0.25
FCPโ‰ค 1.8 s1.8 โ€“ 3.0 s> 3.0 s
TTFBโ‰ค 800 ms800 โ€“ 1800 ms> 1800 ms

CDP counters

CounterTypeMeaning
LayoutDurationCumulativeSeconds in layout
RecalcStyleDurationCumulativeSeconds in style recalc
ScriptDurationCumulativeSeconds executing JS
TaskDurationCumulativeSeconds in main-thread tasks
JSHeapUsedSizeGaugeBytes held
NodesGaugeDOM node count

The reliable-measurement checklist

StepWhy
Warm-up runSkip cold JIT, CSS cache, DNS
Network throttleMatch target device
CPU throttleMatch target device
N runs, medianKill outliers, not average them
Fixed viewportLayout affects CLS
trace: 'off'Snapshotting pollutes the measurement

Best Practices

โœ… Do This:

// Install the observer before navigation
await page.addInitScript(() => { /* observers */ });           // โœ…

// Keep the newest LCP entry, not the largest
window.__vitals.LCP = e[e.length - 1].startTime;                // โœ…

// Sum CLS, skipping input-driven shifts
if (!e.hadRecentInput) window.__vitals.CLS += e.value;          // โœ…

// Throttle to the target device
downloadThroughput: (1.6 * 1024 * 1024) / 8                     // โœ…

// Take the median of several runs
samples.sort((a, b) => a - b); samples[samples.length >> 1]     // โœ…

// Read counters as a delta, not an absolute
a.ScriptDuration - b.ScriptDuration                             // โœ…

// Keep budgets in one config file
export const BUDGET = { LCP: 2500, INP: 200, CLS: 0.1 };        // โœ…

โŒ Don’t Do This:

// Measure the first navigation without warm-up
await page.goto('/');
const t = Date.now(); await page.goto('/');                     // โŒ

// Read `Performance.getMetrics` without enabling
const { metrics } = await client.send('Performance.getMetrics'); // โŒ (empty)

// Assert on the mean of noisy samples
samples.reduce((a, b) => a + b) / samples.length                // โŒ

// Trade correct LCP for the largest single entry
window.__vitals.LCP = e.reduce((m, x) => x.startTime > m ? ...); // โŒ

// Assume `page.metrics()` exists
await page.metrics();                                            // โŒ (Puppeteer)

// Read resource sizes without Timing-Allow-Origin
r.transferSize // 0 for cross-origin without the header           // โŒ

// Leave the trace recorder on for a perf test
test.use({ trace: 'on' });                                        // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Empty metrics arrayPerformance.enable not sentCall it before getMetrics
LCP is 0Observer installed after loadaddInitScript, buffered: true
INP is 0No interaction happenedSimulate the interaction, then read
CLS is 0hadRecentInput filter too eagerLog raw layout-shift entries
Flaky samplesNo warm-upDiscard run 0
Slow CI, fast laptopNo throttleemulateNetworkConditions
transferSize is 0Missing Timing-Allow-OriginDon’t assert on cross-origin sizes
INP under 16 msDefault observer thresholdPass durationThreshold: 16
Heap growth is negativeGC between readsAssert on a repeated-action trend

Real-World Examples

1. Enable the domain

const client = await context.newCDPSession(page);
await client.send('Performance.enable');

2. Read the counters

const { metrics } = await client.send('Performance.getMetrics');

3. Delta a window

task: a.TaskDuration - b.TaskDuration

4. Install the observer

await page.addInitScript(() => {
  new PerformanceObserver(/* ... */).observe({ buffered: true });
});

5. LCP

const e = list.getEntries();
window.__vitals.LCP = e[e.length - 1].startTime;

6. CLS

if (!e.hadRecentInput) window.__vitals.CLS += e.value;

7. TTFB

ttfb: n.responseStart - n.requestStart

8. Throttle

await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });

9. Median

samples.sort((a, b) => a - b);
return samples[Math.floor(samples.length / 2)];

10. Budget

expect(vitals.LCP).toBeLessThanOrEqual(2500);

Visual

The three measurement paths

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THREE MEASUREMENT PATHS IN PLAYWRIGHT                    โ”‚
โ”‚                                                           โ”‚
โ”‚  CDP โ€” Chromium only                                      โ”‚
โ”‚    context.newCDPSession(page)                            โ”‚
โ”‚    โ†’ Performance.enable                                   โ”‚
โ”‚    โ†’ Performance.getMetrics  โ†’  counters                  โ”‚
โ”‚                                                           โ”‚
โ”‚  Performance API โ€” all engines                            โ”‚
โ”‚    page.evaluate(() =>                                    โ”‚
โ”‚      performance.getEntriesByType('navigation'            โ”‚
โ”‚                                    |'resource'))          โ”‚
โ”‚    โ†’ TTFB, DCL, load, subresource waterfall               โ”‚
โ”‚                                                           โ”‚
โ”‚  PerformanceObserver โ€” all engines                        โ”‚
โ”‚    page.addInitScript(() => observer.observe(...))        โ”‚
โ”‚    โ†’ LCP, INP, CLS, FCP                                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

One page load, left to right

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ONE PAGE LOAD, LEFT TO RIGHT                             โ”‚
โ”‚                                                           โ”‚
โ”‚  TTFB         FCP           LCP       INP         CLS     โ”‚
โ”‚   โ”‚            โ”‚             โ”‚         โ”‚           โ”‚      โ”‚
โ”‚   โ–ผ            โ–ผ             โ–ผ         โ–ผ           โ–ผ      โ”‚
โ”‚  โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ–บ   โ”‚
โ”‚  first       first         largest   interaction  shift   โ”‚
โ”‚  byte        content       content   to next      total   โ”‚
โ”‚  arrives     painted       painted   paint        score   โ”‚
โ”‚                                                           โ”‚
โ”‚  โ‰ค 800ms    โ‰ค 1.8s         โ‰ค 2.5s    โ‰ค 200ms     โ‰ค 0.1    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The CDP metrics flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  CDP METRICS FLOW                                         โ”‚
โ”‚                                                           โ”‚
โ”‚  client = context.newCDPSession(page)                     โ”‚
โ”‚      โ”‚                                                    โ”‚
โ”‚      โ–ผ                                                    โ”‚
โ”‚  client.send('Performance.enable')                        โ”‚
โ”‚      โ”‚                                                    โ”‚
โ”‚      โ–ผ                                                    โ”‚
โ”‚  โ”€โ”€โ”€ navigate, interact, wait โ”€โ”€โ”€                         โ”‚
โ”‚      โ”‚                                                    โ”‚
โ”‚      โ–ผ                                                    โ”‚
โ”‚  { metrics } = client.send('Performance.getMetrics')      โ”‚
โ”‚      โ”‚                                                    โ”‚
โ”‚      โ–ผ                                                    โ”‚
โ”‚  delta = after - before  (cumulative โ†’ per-window)        โ”‚
โ”‚                                                           โ”‚
โ”‚  LayoutDuration ยท RecalcStyleDuration ยท ScriptDuration ยท  โ”‚
โ”‚  TaskDuration ยท JSHeapUsedSize ยท Nodes ยท LayoutCount      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The reliable measurement loop

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  RELIABLE MEASUREMENT LOOP                                โ”‚
โ”‚                                                           โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  warm-up run, discard its values        โ”‚
โ”‚  โ”‚   run 0      โ”‚  (JIT, cold CSS, first DNS)             โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                         โ”‚
โ”‚         โ–ผ                                                 โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  identical viewport, cache state,       โ”‚
โ”‚  โ”‚   run 1..N   โ”‚  CPU and network throttle               โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                         โ”‚
โ”‚         โ–ผ                                                 โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  not mean; outliers are the noise       โ”‚
โ”‚  โ”‚    median    โ”‚                                        โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                         โ”‚
โ”‚         โ–ผ                                                 โ”‚
โ”‚  assert median โ‰ค budget                                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Playwright entry pointNo page.metrics(); use CDP or performance
CDP sessioncontext.newCDPSession(page)
CDP domainPerformance.enable โ†’ Performance.getMetrics
CountersLayout, RecalcStyle, Script, Task, Heap
Navigation timingperformance.getEntriesByType('navigation')[0]
Resource timingperformance.getEntriesByType('resource')
Core Web VitalsPerformanceObserver in addInitScript
Network throttleNetwork.emulateNetworkConditions
CPU throttleEmulation.setCPUThrottlingRate
Stable numberWarm-up + N runs + median
BudgetsConstants in one config file

Key takeaways:

  • Playwright does not have page.metrics(). Puppeteer’s convenience method is two lines in Playwright: context.newCDPSession(page) and client.send('Performance.getMetrics'). The counters are the same LayoutDuration, ScriptDuration, TaskDuration, JSHeapUsedSize set, and the Chromium-only constraint is the same.
  • The CDP counters are cumulative, so read them as a delta. Call getMetrics before an action and after it, subtract the two values by name, and the result is the cost of that action. JSHeapUsedSize and Nodes are gauges, so a subtraction can be negative; the trend across a repeated action is the leak signal, not the single delta.
  • The PerformanceObserver must be installed before navigation. page.addInitScript runs first, and buffered: true on each observe call replays the entries the browser emitted before the observer existed. Without both, the vitals are missing or zero.
  • LCP is the newest entry, CLS is a sum, INP needs durationThreshold. Three details inside the observer callbacks decide whether the numbers match Google’s definition. Getting them wrong produces plausible-looking numbers that fail a real budget check.
  • One measurement is a coincidence. A warm-up run, N identical runs against the same throttle, and the median is the pattern that survives a CI runner. The mean is dragged up by a single cold run, and a flaky performance test gets deleted before it catches anything.
  • Throttle to the target device. Network.emulateNetworkConditions and Emulation.setCPUThrottlingRate are what make a measurement on a CI pod resemble a measurement on a mid-range phone. Without them, the test measures the pod’s fiber connection, not the user’s connection.
  • The budgets belong in a shared file. A threshold changed in one test file drifts from the same threshold in another; a single exported BUDGET object keeps LCP, INP, CLS, FCP, and TTFB consistent across the whole suite and revisable once per quarter.

Remember: Performance measurement in Playwright is three paths stitched into one number. The CDP Performance.getMetrics path explains where the main thread spent its time โ€” layout, style, script โ€” and answers the page.metrics() question Puppeteer raises. The performance.getEntriesByType path explains when each byte arrived, from TTFB through the slowest subresource. The PerformanceObserver path explains how the user experienced it, expressed in the five Core Web Vitals and the published thresholds that make the assertion mean something. None of them are worth reading from a single warm-cache run on a laptop; all of them are worth reading as the median of a throttled, warm-up-discarded set, checked against a budget that lives in one file.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!