Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active July 23, 2019 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samarpanda/579f92fd3ddb47a94e6cb17b1e62ed9b to your computer and use it in GitHub Desktop.
Save samarpanda/579f92fd3ddb47a94e6cb17b1e62ed9b to your computer and use it in GitHub Desktop.
Measuring cumulative layout shift score

Measuring cumulative layout shift score

At the moment the layoutShift type is only available when the API is expliciltly enabled. If you are running Chrome 76 or newer, you can start it up via the command line with this flat set:

--enable-blink-features=LayoutInstabilityAPI

Currently this can be captured via WPT Enabling the feature in Chrome Canary

Blog post reference

let cumulativeLayoutShiftScore = 0;
const observer = new PerformanceObserver((list) => {
for(const entry of list.getEntries()){
cumulativeLayoutShiftScore += entry.value;
}
});
observer.observe({entryTypes: ['layoutShift']});
document.addEventListener('visibilitychange', () => {
if(document.visibilityState === 'hidden'){
observer.takeRecords();
sendToAnalytics({cumulativeLayoutShiftScore});
}
})
Below snippet can be used in WPT custom metric
[CumulativeLayoutShift]
return new Promise(resolve => {
var CLS = 0;
new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
if(entry.hadRecentInput) return;
CLS += entry.value;
});
resolve(CLS);
}).observe({type: 'layout-shift', buffered: true});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment