Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active June 16, 2023 15:18
Show Gist options
  • Save samarpanda/43397ab0229c89f07eafd5ed3f9b9345 to your computer and use it in GitHub Desktop.
Save samarpanda/43397ab0229c89f07eafd5ed3f9b9345 to your computer and use it in GitHub Desktop.
Largest contentful Paint

I wonder if i can see all the lcp elements instead of getting the eventual lcp element from the performance panel. Below script higlights all lcp elements available on the page. After running the script in console / source - snippet it highlight by a dotten blue line for all lcp elements. This uses browser's PerformanceObserver API to get all lcp elements.

By @samarpanda

/**
 * 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()]
}

Demo screenshots

  • Run the above LCP script from devtools source snippet
  • Hover on 1st LCP element on console to highlight that on the page
  • Hover on 2nd LCP element on console to highlight that on the page
  • Performance panel to show eventual LCP element. Hover on the performance panel to higlight on the page
@samarpanda
Copy link
Author

Hack to get lowest LCP - https://www.devisedlabs.com/blog/largest-contentful-paint-lcp-hack
Although i don't recommend this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment