Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active April 24, 2021 10:21
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/80e596dfbab1e3bf4cd8422bdd4e7786 to your computer and use it in GitHub Desktop.
Save samarpanda/80e596dfbab1e3bf4cd8422bdd4e7786 to your computer and use it in GitHub Desktop.

New York WebPerf 25th Feb

Talk by @samarpanda

CLS

try {
  var 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}`);
      //sendToAnalytics(cumulativeLayoutShiftScore);
    }
  })

} catch(e) {
  console.log(`Browser doesn't support this API`);
}

Hightlight-LCP-Element

/**
 * PerformanceObserver
 */
const po = new PerformanceObserver(list => {
  let entries = list.getEntries();

  entries = dedupe(entries, "startTime");
  
  /**
   * Print all entries of LCP
   */
  entries.forEach((item, i) => {
    console.dir(item);
    console.log(`${i+1} current LCP item : ${item.element}: ${item.startTime}`);
    /**
     * Highlight LCP elements on the page
     */
    item.element ? item.element.style = "border: 5px dotted blue;" : '';
  })
  
  /**
   * LCP is the lastEntry in getEntries Array
   */
  const lastEntry = entries[entries.length - 1];
  /**
   * Print final LCP
   */
  console.log(`LCP is: ${lastEntry.startTime}`);
});

/**
 * Start observing for largest-contentful-paint
 * buffered true getEntries prior to this script execution
 */
po.observe({ type: 'largest-contentful-paint', buffered: true })

function dedupe(arr, key){
  return [...new Map(arr.map(item => [item[key], item])).values()]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment