@@ -16,8 +16,10 @@ import {
1616} from '@sentry/core' ;
1717import { DEBUG_BUILD } from '../debug-build' ;
1818import { addClsInstrumentationHandler } from './instrument' ;
19+ import type { WebVitalReportEvent } from './utils' ;
1920import { msToSec , startStandaloneWebVitalSpan } from './utils' ;
2021import { onHidden } from './web-vitals/lib/onHidden' ;
22+ import { runOnce } from './web-vitals/lib/runOnce' ;
2123
2224/**
2325 * Starts tracking the Cumulative Layout Shift on the current page and collects the value once
@@ -37,16 +39,13 @@ export function trackClsAsStandaloneSpan(): void {
3739 return ;
3840 }
3941
40- let sentSpan = false ;
41- function _collectClsOnce ( ) {
42- if ( sentSpan ) {
43- return ;
44- }
45- sentSpan = true ;
46- if ( pageloadSpanId ) {
47- sendStandaloneClsSpan ( standaloneCLsValue , standaloneClsEntry , pageloadSpanId ) ;
48- }
49- cleanupClsHandler ( ) ;
42+ function _collectClsOnce ( reportEvent : WebVitalReportEvent ) {
43+ runOnce ( ( ) => {
44+ if ( pageloadSpanId ) {
45+ sendStandaloneClsSpan ( standaloneCLsValue , standaloneClsEntry , pageloadSpanId , reportEvent ) ;
46+ }
47+ cleanupClsHandler ( ) ;
48+ } ) ;
5049 }
5150
5251 const cleanupClsHandler = addClsInstrumentationHandler ( ( { metric } ) => {
@@ -59,7 +58,7 @@ export function trackClsAsStandaloneSpan(): void {
5958 } , true ) ;
6059
6160 onHidden ( ( ) => {
62- _collectClsOnce ( ) ;
61+ _collectClsOnce ( 'pagehide' ) ;
6362 } ) ;
6463
6564 // Since the call chain of this function is synchronous and evaluates before the SDK client is created,
@@ -73,7 +72,7 @@ export function trackClsAsStandaloneSpan(): void {
7372 }
7473
7574 const unsubscribeStartNavigation = client . on ( 'beforeStartNavigationSpan' , ( ) => {
76- _collectClsOnce ( ) ;
75+ _collectClsOnce ( 'navigation' ) ;
7776 unsubscribeStartNavigation ?.( ) ;
7877 } ) ;
7978
@@ -88,7 +87,12 @@ export function trackClsAsStandaloneSpan(): void {
8887 } , 0 ) ;
8988}
9089
91- function sendStandaloneClsSpan ( clsValue : number , entry : LayoutShift | undefined , pageloadSpanId : string ) {
90+ function sendStandaloneClsSpan (
91+ clsValue : number ,
92+ entry : LayoutShift | undefined ,
93+ pageloadSpanId : string ,
94+ reportEvent : WebVitalReportEvent ,
95+ ) {
9296 DEBUG_BUILD && logger . log ( `Sending CLS span (${ clsValue } )` ) ;
9397
9498 const startTime = msToSec ( ( browserPerformanceTimeOrigin ( ) || 0 ) + ( entry ?. startTime || 0 ) ) ;
@@ -102,6 +106,8 @@ function sendStandaloneClsSpan(clsValue: number, entry: LayoutShift | undefined,
102106 [ SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME ] : entry ?. duration || 0 ,
103107 // attach the pageload span id to the CLS span so that we can link them in the UI
104108 'sentry.pageload.span_id' : pageloadSpanId ,
109+ // describes what triggered the web vital to be reported
110+ 'sentry.report_event' : reportEvent ,
105111 } ;
106112
107113 // Add CLS sources as span attributes to help with debugging layout shifts
0 commit comments