1
1
import { getCookie } from '@guardian/libs' ;
2
2
import { getCLS , getFCP , getFID , getLCP , getTTFB } from 'web-vitals' ;
3
3
import reportError from 'lib/report-error' ;
4
+ import { forceSendMetrics } from './forceSendMetrics' ;
4
5
import { shouldCaptureMetrics } from './shouldCaptureMetrics' ;
5
6
6
7
type CoreWebVitalsPayload = {
@@ -30,21 +31,19 @@ const jsonData: CoreWebVitalsPayload = {
30
31
ttfb : null ,
31
32
} ;
32
33
34
+ // By default, sample 1% of users
35
+ const userInSample = Math . random ( ) < 1 / 100 ;
36
+ // unless we are forcing metrics for this user because they are participating in an AB test
37
+ // for which we need to capture all metrics
38
+ const captureMetrics = shouldCaptureMetrics ( ) ;
39
+ // or we are force sending for this page view for some other reason with forceSendMetrics.
40
+
33
41
/**
34
- * Sends core web vitals data for a sample of page views to the data lake.
42
+ * Calls functions of web-vitals library to collect core web vitals data, registering callbacks which
43
+ * send it to the data lake for a sample of page views.
35
44
* Equivalent dotcom-rendering functionality is here: https://git.io/JBRIt
36
45
*/
37
46
export const coreVitals = ( ) : void => {
38
- // By default, sample 1% of users
39
- const inSample = Math . random ( ) < 1 / 100 ;
40
-
41
- // Unless we are forcing metrics for this user
42
- const captureMetrics = shouldCaptureMetrics ( ) ;
43
-
44
- if ( ! captureMetrics && ! inSample ) {
45
- return ;
46
- }
47
-
48
47
type CoreVitalsArgs = {
49
48
name : string ;
50
49
value : number ;
@@ -59,6 +58,10 @@ export const coreVitals = (): void => {
59
58
} ;
60
59
61
60
const jsonToSend = ( { name, value } : CoreVitalsArgs ) : void => {
61
+ if ( ! captureMetrics && ! userInSample && ! forceSendMetrics ) {
62
+ return ;
63
+ }
64
+
62
65
switch ( name ) {
63
66
case 'FCP' :
64
67
jsonData . fcp = nineDigitPrecision ( value ) ;
0 commit comments