Junior — Middle
How can a layout shift (Layout Shift) be detected on a page?
sobes.tech AI
Answer from AI
Layout Shift can be detected using browser developer tools and specific metrics:
-
Chrome DevTools: in the "Performance" tab, you can record a page load session and see moments of layout shifts, which are displayed as Layout Shift Events.
-
CLS (Cumulative Layout Shift) metric from Web Vitals shows the total layout shift during the loading time.
-
JavaScript API: using
PerformanceObserver, you can track layout-shift events:
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) {
console.log('Layout shift detected:', entry);
}
}
});
observer.observe({type: 'layout-shift', buffered: true});
This way, you can programmatically detect and analyze layout shifts on the page.