The LayoutShiftAttribution
interface provides debugging information about elements which have shifted.
Instances of LayoutShiftAttribution
are returned in an array by calling LayoutShift.sources
.
The following example finds the element with the highest layout shift score, and returns the element in that entry with the largest size prior to the shift (previousRect
). For more detail on this see Debug Web Vitals in the field.
function getCLSDebugTarget(entries) {
const largestEntry = entries.reduce((a, b) =>
a && a.value > b.value ? a : b,
);
if (largestEntry?.sources?.length) {
const largestSource = largestEntry.sources.reduce((a, b) => {
const area = (el) => el.previousRect.width * el.previousRect.height;
return a.node && area(a) > area(b) ? a : b;
});
if (largestSource) {
return largestSource.node;
}
}
}