LCP trail
Chrome 77+ Edge 79+ Firefox 122+ Safari 26.2+ Details
Tracks every LCP candidate (opens in a new tab) element during page load and highlights each one with a distinct pastel-colored dashed outline, so you can see the full trail from first candidate to final LCP.
Each time the browser promotes a larger element as the new LCP, the snippet assigns the next color in the palette and highlights it. All previous candidates remain visible on the page for easy comparison.
Need timing breakdowns? Use LCP Subparts to identify which phase (TTFB, load delay, load time, render delay) is causing the bottleneck.
See how candidates are promoted
Replay four loads, or move the slider through one, to see when each element becomes a candidate, which ones never do, and how a user input ends the trail:
Snippet
Run it from an AI agent: the prompt uses the CLI to measure any URL and report the result.
// LCP Trail
// Tracks all LCP candidate elements during page load
// https://webperf-snippets.net
(async () => {
if (!PerformanceObserver.supportedEntryTypes?.includes("largest-contentful-paint")) {
console.warn("⚠️ largest-contentful-paint entries are not supported in this browser.");
return { script: "LCP-Trail", status: "unsupported", error: "largest-contentful-paint entries not supported in this browser" };
}
const PALETTE = [
{ color: "#EF4444", name: "Red" },
{ color: "#F97316", name: "Orange" },
{ color: "#22C55E", name: "Green" },
{ color: "#3B82F6", name: "Blue" },
{ color: "#A855F7", name: "Purple" },
{ color: "#EC4899", name: "Pink" },
];
const valueToRating = (ms) =>
ms <= 2500 ? "good" : ms <= 4000 ? "needs-improvement" : "poor";
const RATING = {
good: { icon: "🟢", color: "#0CCE6A" },
"needs-improvement": { icon: "🟡", color: "#FFA400" },
poor: { icon: "🔴", color: "#FF4E42" },
};
const getActivationStart = () => {
const navEntry = performance.getEntriesByType("navigation")[0];
return navEntry?.activationStart || 0;
};
// @shared uniqueSelector
// A CSS selector that matches only el in its document (or shadow root): its id when it is unique,
// otherwise a path of tag, classes and :nth-of-type() that goes up to the nearest ancestor with a
// unique id, or to the root, and stops as soon as it matches one element.
function uniqueSelector(el) {
const root = el.getRootNode();
const matchesOne = (selector) => {
try {
return root.querySelectorAll(selector).length === 1;
} catch {
return false;
}
};
const parts = [];
let node = el;
while (node && node.nodeType === 1) {
if (node.id && matchesOne(`#${window.CSS.escape(node.id)}`)) {
parts.unshift(`#${window.CSS.escape(node.id)}`);
break;
}
const tag = node.localName;
let part = tag + Array.from(node.classList).slice(0, 2).map((c) => `.${window.CSS.escape(c)}`).join("");
const siblings = node.parentNode ? Array.from(node.parentNode.children) : [node];
if (siblings.filter((s) => s.matches(part)).length > 1) {
part += `:nth-of-type(${siblings.filter((s) => s.localName === tag).indexOf(node) + 1})`;
}
parts.unshift(part);
if (matchesOne(parts.join(" > "))) break;
node = node.parentElement;
}
return parts.join(" > ");
}
// @end-shared uniqueSelector
// The element of an entry is null once its node has left the DOM, as with a loading spinner that
// an app removes when it renders. The entry keeps its time, size and URL.
const REMOVED = "(removed from DOM)";
// The kind of an LCP element, and the URL of its image when it has one
const describeLcpElement = (element, entry) => {
if (!element) return entry.url ? { type: "Image", url: entry.url } : { type: "Removed element" };
const tag = element.tagName.toLowerCase();
if (tag === "img") return { type: "Image", url: entry.url || element.src };
if (tag === "video") return { type: "Video poster", url: entry.url || element.poster };
if (window.getComputedStyle(element).backgroundImage !== "none") return { type: "Background image", url: entry.url };
return { type: tag === "h1" || tag === "p" ? "Text block" : tag };
};
// One candidate per element, or per entry when its element was removed
const candidateKey = (entry) => entry.element ?? `${entry.startTime}|${entry.size}`;
// @shared urlLabel
// A URL short enough for the console: the file name, with the host when it is another one
function urlLabel(url) {
if (url.startsWith("data:")) return `${url.split(",")[0]},…`;
try {
const u = new URL(url);
const file = u.pathname.split("/").pop()?.split("?")[0];
return u.hostname !== location.hostname ? `${u.hostname}/…/${file}` : file || url;
} catch {
return url;
}
}
// @end-shared urlLabel
// @shared hiddenBefore
// Whether the page was hidden before `time`, a startTime: it loaded in a background tab, or the user
// switched to another tab before it painted. A paint nobody saw is not the metric, and web-vitals does
// not report it. The first visibility-state entry "hidden" says when, as in web-vitals: a prerendered
// page is hidden until its activation, so only an entry from the activation on counts. Without one, the
// page was hidden from its start only if it is hidden now.
function hiddenBefore(time) {
if (PerformanceObserver.supportedEntryTypes?.includes("visibility-state") && !document.prerendering) {
const activationStart = performance.getEntriesByType("navigation")[0]?.activationStart || 0;
const hidden = performance
.getEntriesByType("visibility-state")
.find((entry) => entry.name === "hidden" && entry.startTime >= activationStart);
if (hidden) return hidden.startTime <= time;
}
return document.visibilityState === "hidden" && !document.prerendering;
}
// Why a snippet gives no value for a metric the page painted while it was hidden
function hiddenMessage(metric) {
return `The page was hidden before its ${metric} was painted, as when it loads in a background tab or the user switches to another tab before it paints, so the ${metric} is not what a user saw and web-vitals does not report it. Reload the page with its tab in front and run the snippet again.`;
}
// The result of a snippet whose metric the page painted while it was hidden: hiddenBeforePaint tells the
// reports that it measured nothing, and that neither the snippet nor the page failed
function hiddenResult(name, metric) {
return { script: name, status: "error", hiddenBeforePaint: true, error: hiddenMessage(metric) };
}
// The warning of the console, once however many times the page paints while it is hidden
let hiddenWarned = false;
function warnHidden(metric) {
if (!hiddenWarned) console.warn(`⚠️ ${hiddenMessage(metric)}`);
hiddenWarned = true;
}
// @end-shared hiddenBefore
const candidates = [];
const logTrail = () => {
const current = candidates[candidates.length - 1];
if (!current) return;
const rating = valueToRating(current.time);
const { icon, color: ratingColor } = RATING[rating];
console.group(
`%cLCP: ${icon} ${(current.time / 1000).toFixed(2)}s (${rating})`,
`color: ${ratingColor}; font-weight: bold; font-size: 14px;`
);
// Current LCP element attribution
console.log("");
console.log("%cLCP Element:", "font-weight: bold;");
if (current.element) console.log(` Element: ${current.selector}`, current.element);
else console.log(` Element: ${REMOVED}${current.entry.id ? ` #${current.entry.id}` : ""}`);
const { type, url } = describeLcpElement(current.element, current.entry);
console.log(` Type: ${type}`);
if (url) console.log(` URL: ${urlLabel(url)}`);
if (current.element?.naturalWidth) {
console.log(
` Dimensions: ${current.element.naturalWidth}×${current.element.naturalHeight}`
);
}
if (current.entry.size) {
console.log(` Size: ${current.entry.size.toLocaleString()} px²`);
}
// Trail legend
console.log("");
console.log("%cCandidates Trail:", "font-weight: bold;");
candidates.forEach(({ index, selector, color, name, time, element }) => {
const isCurrent = index === candidates.length;
console.log(
`%c ● ${index}. ${selector}`,
`color: ${color}; font-weight: ${isCurrent ? "bold" : "normal"};`,
`| ${(time / 1000).toFixed(2)}s${element ? ` — ${name}` : ""}${isCurrent ? " ← LCP" : ""}`,
...(element ? [element] : [])
);
});
console.log("");
console.log(
"%c✓ Each candidate in the DOM highlighted with a colored dashed outline",
"color: #22c55e;"
);
console.groupEnd();
};
// The candidates painted after the page was hidden are not part of the trail of its LCP
const observer = new PerformanceObserver((list) => {
const shown = list.getEntries().filter((entry) => !hiddenBefore(entry.startTime));
if (shown.length === 0) {
if (candidates.length === 0) warnHidden("LCP");
return;
}
const activationStart = getActivationStart();
const seen = new Set(candidates.map((c) => candidateKey(c.entry)));
for (const entry of shown) {
const key = candidateKey(entry);
if (seen.has(key)) continue;
seen.add(key);
const { element } = entry;
const { color, name } = PALETTE[candidates.length % PALETTE.length];
if (element) {
element.style.outline = `3px dashed ${color}`;
element.style.outlineOffset = "2px";
}
candidates.push({
index: candidates.length + 1,
element,
selector: element ? uniqueSelector(element) : REMOVED,
color: element ? color : "#9CA3AF",
name,
time: Math.max(0, entry.startTime - activationStart),
entry,
});
}
logTrail();
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
console.log("%c⏱️ LCP Trail Active", "font-weight: bold; font-size: 14px;");
console.log(" Highlights all LCP candidate elements with distinct colors.");
// Return for agent (buffered entries)
// Chrome only exposes largest-contentful-paint entries through a PerformanceObserver,
// so performance.getEntriesByType() returns [] here. Collect via a buffered observer.
const lcpEntries = await new Promise((resolve) => {
const entries = [];
const obs = new PerformanceObserver((list) => entries.push(...list.getEntries()));
obs.observe({ type: "largest-contentful-paint", buffered: true });
setTimeout(() => { obs.disconnect(); resolve(entries); }, 100);
});
if (lcpEntries.length === 0) {
return { script: "LCP-Trail", status: "error", error: "No LCP entries yet" };
}
// The trail ends at the last candidate painted before the page was hidden, its LCP; without one, the
// page painted every candidate while nobody saw it
const trailEntries = lcpEntries.filter((entry) => !hiddenBefore(entry.startTime));
if (trailEntries.length === 0) return hiddenResult("LCP-Trail", "LCP");
const trailActivationStart = getActivationStart();
const byKey = new Map();
for (const entry of trailEntries) {
const key = candidateKey(entry);
if (byKey.has(key)) continue;
const el = entry.element;
const { type, url } = describeLcpElement(el, entry);
byKey.set(key, {
index: byKey.size + 1,
selector: el ? uniqueSelector(el) : null,
...(el ? {} : { removed: true }),
...(!el && entry.id ? { id: entry.id } : {}),
time: Math.round(Math.max(0, entry.startTime - trailActivationStart)),
elementType: type,
sizePixels: entry.size,
...(url ? { url: urlLabel(url) } : {}),
});
}
const syncCandidates = [...byKey.values()];
// The LCP is the last entry, whether or not its element is still in the DOM
const lastEntry = trailEntries.at(-1);
const lastCandidate = byKey.get(candidateKey(lastEntry));
const trailValue = Math.round(Math.max(0, lastEntry.startTime - trailActivationStart));
const trailRating = valueToRating(trailValue);
return {
script: "LCP-Trail",
status: "ok",
metric: "LCP",
value: trailValue,
unit: "ms",
rating: trailRating,
thresholds: { good: 2500, needsImprovement: 4000 },
details: {
candidateCount: syncCandidates.length,
finalElement: lastCandidate.selector,
candidates: syncCandidates,
},
};
})();
How it works
The snippet observes largest-contentful-paint entries with buffered: true, which captures all candidates since navigation started. Each time the browser promotes a new element as the current LCP:
- The element receives a dashed outline in the next palette color
- The console logs are updated with attribution for the current LCP
- The Candidates Trail legend shows every candidate in order, with its color, time, and a clickable element reference
A candidate whose element has left the DOM, such as a loading spinner that the app removes when it renders, stays in the trail as (removed from DOM), with its time and, for an image, its URL, but without an outline. The snippet reads the entries once the page has loaded, so the spinner is often gone by then, and it is the LCP that field data reports for the users who leave before the app renders. The LCP is the last candidate, whether or not its element is still in the DOM.
Multiple candidates appear when
- An image loads after a text element that was initially larger in the viewport
- A hero image replaces a heading as the largest content
- Lazy-loaded or late-loading resources become the largest visible element
A page hidden before it painted
A page that loads in a background tab, or that the user leaves for another tab before it paints, paints while nobody sees it, so its LCP is not what a user waited for, and web-vitals does not report it. The snippet returns an error with that reason instead of a time: reload the page with its tab in front and run it again. A prerendered page is hidden until its activation, and that does not count. A page hidden after it painted keeps its LCP: the last candidate painted before it was hidden, as in web-vitals, and not one painted later.
Browser support
| Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
| LargestContentfulPaint (opens in a new tab) | 77 | 79 | 122 | 26.2 |
| PerformanceObserver (opens in a new tab) | 52 | 79 | 57 | 11 |
| PerformanceNavigationTiming (opens in a new tab) | 57 | 12 | 58 | 15 |
| All of the above | 77 | 79 | 122 | 26.2 |
Source: MDN browser compatibility data (opens in a new tab), version 8.1.10.
Further reading
- Largest Contentful Paint (LCP) (opens in a new tab) | web.dev
- LCP element candidates (opens in a new tab) | web.dev
- LCP | Quick LCP check
- LCP Subparts | Detailed phase breakdown
- FCP | First Contentful Paint, the earliest paint signal before LCP