From 38fd5b716ec4671b459258b887ad102562101db4 Mon Sep 17 00:00:00 2001 From: Barry Pollard Date: Fri, 24 Mar 2023 19:38:26 +0000 Subject: [PATCH] Correct LCP breakdown code and add warning on prerendered pages (#9809) --- .../content/en/blog/optimize-lcp/index.md | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/site/content/en/blog/optimize-lcp/index.md b/src/site/content/en/blog/optimize-lcp/index.md index f4969d0a071..473fdacb0f7 100644 --- a/src/site/content/en/blog/optimize-lcp/index.md +++ b/src/site/content/en/blog/optimize-lcp/index.md @@ -6,7 +6,7 @@ authors: - philipwalton - tunetheweb date: 2020-05-05 -updated: 2022-09-27 +updated: 2022-03-24 hero: image/admin/qqTKhxUFqdLXnST2OFWN.jpg alt: Optimize LCP banner description: | @@ -431,8 +431,10 @@ new PerformanceObserver((list) => { ); const lcpRenderTime = Math.max( lcpResponseEnd, - // Prefer `renderTime` (if TOA is set), otherwise use `loadTime`. - lcpEntry ? lcpEntry.renderTime || lcpEntry.loadTime : 0 + // Use LCP startTime (which is the final LCP time) as sometimes + // slight differences between loadTime/renderTime and startTime + // due to rounding precision. + lcpEntry ? lcpEntry.startTime : 0 ); // Clear previous measures before making new ones. @@ -477,6 +479,18 @@ new PerformanceObserver((list) => { You can use this code as-is for local debugging, or modify it to send this data to an analytics provider so you can get a better understanding of what the breakdown of LCP is on your pages for real users. +{% Aside warning %} +

+The above code works for standard navigations, but extra consideration must be taken for [prerendered pages](https://developer.chrome.com/blog/prerender-pages/), which should be measured from the activation start time but which has been kept out of this code for simplicity. +

+

+The [web-vitals library](https://github.com/GoogleChrome/web-vitals) includes this breakdown in the attribution build, and includes these considerations. +

+

+For those looking to implement their own solution, the [code for this is open source](https://github.com/GoogleChrome/web-vitals/blob/main/src/attribution/onLCP.ts) and is similar to above but with extra lofic for activation start. +

+{% endAside %} + ## Summary LCP is complex, and its timing can be affected by a number of factors. But if you consider that optimizing LCP is primarily about optimizing the load of the LCP resource, it can significantly simplify things.