Skip to the code

Observe CLS

Write onCLS(report), which measures Cumulative Layout Shift on a live page and reports it as onCLS in web-vitals 6.2.3 does. Group the shifts with the rules of the cls-session-windows problem: skip a shift whose hadRecentInput is true; a shift joins the current window when it starts less than 1000 ms after the window's last shift and less than 5000 ms after its first, and otherwise starts a new window; a window's score is the sum of its shifts' values. CLS is the highest score a window has reached, so it changes only when the current window's score goes above it.

Watch shifts with a PerformanceObserver, observing { type: "layout-shift", buffered: true }, and do nothing at all where PerformanceObserver.supportedEntryTypes doesn't list the type. Shifts arrive a few at a time, so keep the current window between callbacks: a shift can join a window whose other shifts came in an earlier one.

Report when the page is hidden: on a visibilitychange event that finds document.visibilityState is "hidden". First run the observer's takeRecords() through the same code, for shifts the browser hasn't delivered yet. Then call report with a plain object { name: "CLS", value, delta, entries }: the CLS, how much it changed since the last report (the whole value the first time), and the shifts of the window that set it. The first hide always reports, even a CLS of 0. A later hide reports only if CLS changed since the last report: people come back to a tab, and the page can shift again.

web-vitals also waits for First Contentful Paint before it starts, as the Chrome UX Report does, and starts over after a back/forward cache restore. Leave both out.

onCLS((metric) => console.log(metric.value, metric.delta));
// The tea photos load in and push the menu down: shifts of 0.25 and 0.125.
// The reader switches tabs: 0.375 0.375
// They come back, and a late banner shifts the page by 0.5.
// They switch tabs again: 0.5 0.125

What the tests check

  1. watches buffered layout-shift entries, and reports the largest window when the page is hidden, not before
    const perf = usePerformance();
    const shift = (startTime, value, hadRecentInput = false) => ({ startTime, value, hadRecentInput });
    const [early] = perf.buffer("layout-shift", [shift(900, 0.125)]);
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    expect(perf.observers().map((observer) => [observer.types, observer.buffered])).toEqual([[["layout-shift"], true]]);
    await flush();
    const later = perf.emit("layout-shift", [shift(1400, 0.25), shift(1900, 0.125)]);
    await flush();
    expect(reports).toEqual([]);
    setVisibility("hidden");
    expect(reports).toEqual([{ name: "CLS", value: 0.5, delta: 0.5, entries: [early, ...later] }]);
    
  2. a page that never shifted reports a CLS of 0 the first time it's hidden, and only then
    usePerformance();
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    setVisibility("hidden");
    expect(reports).toEqual([{ name: "CLS", value: 0, delta: 0, entries: [] }]);
    setVisibility("visible");
    setVisibility("hidden");
    expect(reports).toHaveLength(1);
    
  3. windows grow across callbacks, and a shift right after input neither counts nor keeps a window open
    const perf = usePerformance();
    const shift = (startTime, value, hadRecentInput = false) => ({ startTime, value, hadRecentInput });
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    perf.emit("layout-shift", [shift(1000, 0.125)]);
    perf.emit("layout-shift", [shift(1500, 0.125)]);
    perf.emit("layout-shift", [shift(2000, 0.5, true)]); // right after a tap on "Add to basket"
    const [banner] = perf.emit("layout-shift", [shift(2800, 0.25)]); // 1300 ms after the last shift that counts
    const [footer] = perf.emit("layout-shift", [shift(3400, 0.125)]);
    const [reviews] = perf.emit("layout-shift", [shift(4100, 0.0625)]);
    setVisibility("hidden");
    expect(reports).toEqual([{ name: "CLS", value: 0.4375, delta: 0.4375, entries: [banner, footer, reviews] }]);
    
  4. a later hide reports again only when CLS has changed, with the change as its delta
    const perf = usePerformance();
    const shift = (startTime, value, hadRecentInput = false) => ({ startTime, value, hadRecentInput });
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    const first = perf.emit("layout-shift", [shift(1000, 0.125), shift(1500, 0.125)]);
    setVisibility("hidden");
    setVisibility("visible");
    setVisibility("hidden");
    setVisibility("visible");
    perf.emit("layout-shift", [shift(10000, 0.125)]); // a smaller window: CLS stays 0.25
    setVisibility("hidden");
    setVisibility("visible");
    const late = perf.emit("layout-shift", [shift(20000, 0.25), shift(20500, 0.125)]);
    setVisibility("hidden");
    expect(reports).toEqual([
      { name: "CLS", value: 0.25, delta: 0.25, entries: first },
      { name: "CLS", value: 0.375, delta: 0.125, entries: late },
    ]);
    
  5. shifts the observer hasn't delivered yet count when the page is hidden, and only once
    const perf = usePerformance();
    const shifts = perf.buffer("layout-shift", [{ startTime: 400, value: 0.25, hadRecentInput: false }]);
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    setVisibility("hidden"); // before the buffered shift has been delivered
    expect(reports).toEqual([{ name: "CLS", value: 0.25, delta: 0.25, entries: shifts }]);
    await flush();
    setVisibility("visible");
    setVisibility("hidden");
    expect(reports).toHaveLength(1);
    
  6. does nothing where the browser has no layout-shift entries
    const perf = usePerformance();
    perf.supported(["event", "first-input", "largest-contentful-paint", "mark", "measure", "navigation", "paint", "resource"]);
    const reports = [];
    onCLS((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
    expect(perf.observers()).toEqual([]);
    setVisibility("hidden");
    expect(reports).toEqual([]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).