From 37449fb5d4e4cbbe80e4167597094cfd04707b5f Mon Sep 17 00:00:00 2001 From: Barry Pollard Date: Mon, 6 Mar 2023 14:11:04 +0000 Subject: [PATCH] Prevent LCP being reported for hidden prerendered page --- src/onLCP.ts | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/onLCP.ts b/src/onLCP.ts index c7586929..bf24ac7b 100644 --- a/src/onLCP.ts +++ b/src/onLCP.ts @@ -54,17 +54,18 @@ export const onLCP = (onReport: ReportCallback, opts?: ReportOpts) => { const handleEntries = (entries: LCPMetric['entries']) => { const lastEntry = entries[entries.length - 1] as LargestContentfulPaint; if (lastEntry) { - // The startTime attribute returns the value of the renderTime if it is - // not 0, and the value of the loadTime otherwise. The activationStart - // reference is used because LCP should be relative to page activation - // rather than navigation start if the page was prerendered. But in cases - // where `activationStart` occurs after the LCP, this time should be - // clamped at 0. - const value = Math.max(lastEntry.startTime - getActivationStart(), 0); - // Only report if the page wasn't hidden prior to LCP. - if (value < visibilityWatcher.firstHiddenTime) { - metric.value = value; + if (lastEntry.startTime < visibilityWatcher.firstHiddenTime) { + // The startTime attribute returns the value of the renderTime if it is + // not 0, and the value of the loadTime otherwise. The activationStart + // reference is used because LCP should be relative to page activation + // rather than navigation start if the page was prerendered. But in cases + // where `activationStart` occurs after the LCP, this time should be + // clamped at 0. + metric.value = Math.max( + lastEntry.startTime - getActivationStart(), + 0 + ); metric.entries = [lastEntry]; report(); }