diff --git a/packages/tracing/src/browser/metrics.ts b/packages/tracing/src/browser/metrics.ts index 93253fcf2d0f..555a508df385 100644 --- a/packages/tracing/src/browser/metrics.ts +++ b/packages/tracing/src/browser/metrics.ts @@ -21,6 +21,7 @@ export class MetricsInstrumentation { private _performanceCursor: number = 0; private _lcpEntry: LargestContentfulPaint | undefined; private _clsEntry: LayoutShift | undefined; + private _reportLCP: ReturnType; public constructor(private _reportAllChanges: boolean = false) { if (!isNodeEnv() && global && global.performance && global.document) { @@ -43,6 +44,12 @@ export class MetricsInstrumentation { logger.log('[Tracing] Adding & adjusting spans using Performance API'); + // `addPerformanceEntries` should be called on transaction.finish + // If we are finishing a transaction, we should force report the LCP. + if (this._reportLCP) { + this._reportLCP(true); + } + const timeOrigin = msToSec(browserPerformanceTimeOrigin); let responseStartTimestamp: number | undefined; @@ -223,7 +230,7 @@ export class MetricsInstrumentation { /** Starts tracking the Largest Contentful Paint on the current page. */ private _trackLCP(): void { - getLCP(metric => { + this._reportLCP = getLCP(metric => { const entry = metric.entries.pop(); if (!entry) { return; diff --git a/packages/tracing/src/browser/web-vitals/getLCP.ts b/packages/tracing/src/browser/web-vitals/getLCP.ts index 8b00dc417746..415f53523e99 100644 --- a/packages/tracing/src/browser/web-vitals/getLCP.ts +++ b/packages/tracing/src/browser/web-vitals/getLCP.ts @@ -34,10 +34,13 @@ export interface LargestContentfulPaint extends PerformanceEntry { const reportedMetricIDs: Record = {}; -export const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): void => { +export const getLCP = ( + onReport: ReportHandler, + reportAllChanges?: boolean, +): ReturnType | undefined => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric('LCP'); - let report: ReturnType; + let report: ReturnType | undefined; const entryHandler = (entry: PerformanceEntry): void => { // The startTime attribute returns the value of the renderTime if it is not 0, @@ -66,7 +69,9 @@ export const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): voi po.takeRecords().map(entryHandler as PerformanceEntryHandler); po.disconnect(); reportedMetricIDs[metric.id] = true; - report(true); + if (report) { + report(true); + } } }; @@ -79,4 +84,6 @@ export const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): voi onHidden(stopListening, true); } + + return report; };