Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active June 26, 2020 19:43
Show Gist options
  • Select an option

  • Save samarpanda/a5f561fc6af83883494f03544fba4664 to your computer and use it in GitHub Desktop.

Select an option

Save samarpanda/a5f561fc6af83883494f03544fba4664 to your computer and use it in GitHub Desktop.
Calculative Cumulative Layout Shift(CLS) performance metric

Cumulative layout shift (CLS)

Using web-vitals npm package

import {getCLS} from 'web-vitals';
getCLS(console.log);

Devtools snippet to measure CLS

try {
  let cumulativeLayoutShiftScore = 0;
  const observer = new PerformanceObserver(list => {
    for(const entry of list.getEntries()){
      if(!entry.hadRecentInput){
        cumulativeLayoutShiftScore += entry.value;
      }
    }
  });

  observer.observe({type: 'layout-shift', buffered: true});

  document.addEventListener('visibilitychange', () => {
    if(document.visibilityState === 'hidden'){
      observer.takeRecords();
      observer.disconnect();
      
      console.log(`CLS: ${cumulativeLayoutShiftScore}`);
    }
  })

} catch(e) {
  console.log(`Browser doesn't support this API`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment