Created
March 19, 2022 09:23
-
-
Save nucliweb/1be3b4bac9f676fbb70be74c74c855c4 to your computer and use it in GitHub Desktop.
Get LCP Metrics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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