What CLS do these layout shifts add up to?
A product page's PerformanceObserver collected these layout-shift entries. The code groups them the way the web-vitals library does and logs each group's total, then the page's CLS and its rating. What does it log?
// The layout-shift entries a PerformanceObserver saw on the tea shop's product page.
// startTime is in milliseconds after the navigation started.
const shifts = [
{ startTime: 400, value: 0.05, hadRecentInput: false }, // the hero picture arrives
{ startTime: 900, value: 0.04, hadRecentInput: false }, // the web font swaps in
{ startTime: 1500, value: 0.02, hadRecentInput: false }, // the review stars load
{ startTime: 3200, value: 0.2, hadRecentInput: true }, // "Show reviews" opens, right after a tap
{ startTime: 6000, value: 0.03, hadRecentInput: false }, // a cookie banner slides in
{ startTime: 6400, value: 0.06, hadRecentInput: false }, // an ad fills its slot
];
// Session windows, as web-vitals groups them.
const windows = [];
for (const shift of shifts) {
if (shift.hadRecentInput) continue;
const current = windows.at(-1);
if (current && shift.startTime - current.last < 1000 && shift.startTime - current.first < 5000) {
current.value += shift.value;
current.last = shift.startTime;
} else {
windows.push({ first: shift.startTime, last: shift.startTime, value: shift.value });
}
}
for (const { first, value } of windows) console.log(`Window from ${first} ms: ${value.toFixed(2)}`);
const cls = Math.max(...windows.map((item) => item.value));
const rating = cls > 0.25 ? "poor" : cls > 0.1 ? "needs-improvement" : "good";
console.log(`CLS: ${cls.toFixed(2)} (${rating})`);
Practice it in the editor, with tests
The answer
Work out every line it logs, in order. Then check.
Checking your sign-in…