Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active June 23, 2020 17:22
Show Gist options
  • Select an option

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

Select an option

Save samarpanda/005a3fe775ca220feadcf43bca6e5040 to your computer and use it in GitHub Desktop.
How to measure largest contentful paint

Largest contentful paint

const po = new PerformanceObserver(list => {
  const entries = list.getEntries();
  const lastEntry = entries[entries.length - 1];
  console.log(`LCP is: ${lastEntry.startTime}`);
});
po.observe({ type: 'largest-contentful-paint', buffered: true })

Using Element Timing API (Fallback)

<img src="hero.jpg" elementtiming="the-hero">
new PerformanceObserver(list => {
  for(const entry of list.getEntries()){
    console.log(`Element ${entry.identifier} painted at ${entry.startTime}`);
  };
}).observe.({type: 'element'});

DevTools source panel snippet

Highlight LCP elements by dotted blue border

/**
 * 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