Skip to content

Instantly share code, notes, and snippets.

@rviscomi
Created May 25, 2023 15:47
Show Gist options
  • Save rviscomi/ec9a78ac4bb2c2ec141a3dd27c7ab805 to your computer and use it in GitHub Desktop.
Save rviscomi/ec9a78ac4bb2c2ec141a3dd27c7ab805 to your computer and use it in GitHub Desktop.
WebPageTest custom metric to measure the LCP resource load delay diagnostic.
[lcp_rld]
// https://web.dev/optimize-lcp/#monitor-lcp-breakdown-in-javascript
return new Promise(resolve => {
new PerformanceObserver((list) => {
const lcpEntry = list.getEntries().at(-1);
const navEntry = performance.getEntriesByType('navigation')[0];
const lcpResEntry = performance
.getEntriesByType('resource')
.filter((e) => e.name === lcpEntry.url)[0];
// Ignore LCP entries that aren't images to reduce DevTools noise.
// Comment this line out if you want to include text entries.
if (!lcpEntry.url) return;
// Compute the start and end times of each LCP sub-part.
// WARNING! If your LCP resource is loaded cross-origin, make sure to add
// the `Timing-Allow-Origin` (TAO) header to get the most accurate results.
const ttfb = navEntry.responseStart;
const lcpRequestStart = Math.max(
ttfb,
// Prefer `requestStart` (if TOA is set), otherwise use `startTime`.
lcpResEntry ? lcpResEntry.requestStart || lcpResEntry.startTime : 0
);
resolve(lcpRequestStart - ttfb);
}).observe({type: 'largest-contentful-paint', buffered: true});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment