Write onLCP(report), the live half of measuring Largest Contentful Paint. Each time something larger paints, the browser records a new largest-contentful-paint entry, a candidate, and onLCP calls report once with the candidate that counts, as onLCP in web-vitals 6.2.3 does. The final-lcp problem picks that candidate from a finished timeline; here you wire up the observer and the events that decide it, on a live page.
Watch candidates with one PerformanceObserver, observing { type: "largest-contentful-paint", buffered: true }, so candidates painted before your code ran arrive too. Each candidate replaces the one before. Where PerformanceObserver.supportedEntryTypes doesn't list the type, do nothing at all.
Stop at the reader's first key press or click, or when the page is hidden. Listen for keydown, click, and visibilitychange on window, in the capture phase, so a handler that stops an event can't keep it from you. When one arrives and document.visibilityState is "hidden", stop at once. Otherwise stop in the next idle callback, requestIdleCallback(stop, { timeout: 1000 }), so the work stays out of the interaction, or with setTimeout(stop, 0) where there's no requestIdleCallback. A candidate that arrives before you stop still counts. Other events, like pointermove, keyup, or scroll, change nothing.
Stop only once: disconnect the observer, remove the three listeners, and, if there is a candidate, call report with a plain object { name: "LCP", value, delta, entries }. value is the candidate's startTime, delta is the same number (this is the only report), and entries holds the candidate. With no candidate, report nothing.
Two parts of web-vitals stay out. It ignores events a script made, whose isTrusted is false, but every event in these tests comes from a script, so leave that check out. And it measures prerendered pages and pages opened in a background tab differently, which final-lcp covers.
onLCP((metric) => navigator.sendBeacon("/analytics", JSON.stringify(metric)));
// The shop's name paints at 820 ms, the oolong photo at 1460 ms.
// The reader taps "Add to basket", and in the next idle callback this reports:
// { name: "LCP", value: 1460, delta: 1460, entries: [the oolong candidate] }
const perf = usePerformance();
const [, photo] = perf.buffer("largest-contentful-paint", [
{ startTime: 820, size: 14000, url: "" },
{ startTime: 1460, size: 96000, url: "/teas/oolong.avif" },
]);
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
const observers = perf.observers();
expect(observers).toHaveLength(1);
expect(observers[0].types).toEqual(["largest-contentful-paint"]);
expect(observers[0].buffered).toBe(true);
await flush();
expect(reports).toEqual([]);
setVisibility("hidden");
expect(reports).toEqual([{ name: "LCP", value: 1460, delta: 1460, entries: [photo] }]);
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
const [photo] = perf.emit("largest-contentful-paint", { startTime: 1460, size: 96000, url: "/teas/oolong.avif" });
await flush();
setVisibility("hidden");
expect(reports).toEqual([{ name: "LCP", value: 1460, delta: 1460, entries: [photo] }]);
expect(perf.observers()[0].disconnected).toBe(true);
setVisibility("visible");
perf.emit("largest-contentful-paint", { startTime: 9000, size: 120000, url: "/offers/banner.avif" });
setVisibility("hidden");
await flush();
expect(reports).toHaveLength(1);
const clock = useFakeTimers();
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
clock.tick(1500);
fire(document.querySelector("#add"), "click");
// Painted just before the click, delivered just after it.
const [photo] = perf.emit("largest-contentful-paint", { startTime: 1460, size: 96000, url: "/teas/oolong.avif" });
expect(reports).toEqual([]);
await clock.runAllAsync();
expect(reports).toEqual([{ name: "LCP", value: 1460, delta: 1460, entries: [photo] }]);
expect(perf.observers()[0].disconnected).toBe(true);
fire(document.body, "keydown", { key: "Enter" });
setVisibility("hidden");
await clock.runAllAsync();
expect(reports).toHaveLength(1);
const clock = useFakeTimers();
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
fire(document.body, "pointermove");
fire(document.body, "scroll");
fire(document.body, "keyup", { key: "Tab" });
await clock.runAllAsync();
expect(reports).toEqual([]);
const [photo] = perf.emit("largest-contentful-paint", { startTime: 1460, size: 96000, url: "/teas/oolong.avif" });
fire(document.querySelector("#add"), "keydown", { key: "Enter" });
await clock.runAllAsync();
expect(reports).toEqual([{ name: "LCP", value: 1460, delta: 1460, entries: [photo] }]);
const clock = useFakeTimers();
const perf = usePerformance();
const button = document.querySelector("#add");
button.addEventListener("click", (event) => event.stopPropagation());
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
const [heading] = perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
fire(button, "click");
await clock.runAllAsync();
expect(reports).toEqual([{ name: "LCP", value: 820, delta: 820, entries: [heading] }]);
const clock = useFakeTimers();
clock.idleBudget = 0;
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
fire(document.querySelector("#add"), "click");
const [photo] = perf.emit("largest-contentful-paint", { startTime: 1460, size: 96000, url: "/teas/oolong.avif" });
setVisibility("hidden");
expect(reports).toEqual([{ name: "LCP", value: 1460, delta: 1460, entries: [photo] }]);
await clock.runAllAsync();
expect(reports).toHaveLength(1);
const clock = useFakeTimers();
clock.idleBudget = 0;
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
const [heading] = perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
fire(document.querySelector("#add"), "click");
await clock.tickAsync(999);
expect(reports).toEqual([]);
await clock.tickAsync(1);
expect(reports).toEqual([{ name: "LCP", value: 820, delta: 820, entries: [heading] }]);
const clock = useFakeTimers({ idleCallbacks: false });
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
const [heading] = perf.emit("largest-contentful-paint", { startTime: 820, size: 14000, url: "" });
fire(document.querySelector("#add"), "click");
expect(reports).toEqual([]);
await clock.tickAsync(0);
expect(reports).toEqual([{ name: "LCP", value: 820, delta: 820, entries: [heading] }]);
const clock = useFakeTimers();
const perf = usePerformance();
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
fire(document.querySelector("#add"), "click");
await clock.runAllAsync();
perf.emit("largest-contentful-paint", { startTime: 2100, size: 96000, url: "/teas/oolong.avif" });
setVisibility("hidden");
await clock.runAllAsync();
expect(reports).toEqual([]);
const perf = usePerformance();
perf.supported(["event", "first-input", "layout-shift", "mark", "measure", "navigation", "paint", "resource"]);
const reports = [];
onLCP((metric) => reports.push({ ...metric, entries: [...metric.entries] }));
expect(perf.observers()).toEqual([]);
setVisibility("hidden");
await flush();
expect(reports).toEqual([]);
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).
I'm here to help with Observe LCP. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.