1 | /*
|
2 | * Copyright 2020 Google LLC
|
3 | *
|
4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | * you may not use this file except in compliance with the License.
|
6 | * You may obtain a copy of the License at
|
7 | *
|
8 | * https://www.apache.org/licenses/LICENSE-2.0
|
9 | *
|
10 | * Unless required by applicable law or agreed to in writing, software
|
11 | * distributed under the License is distributed on an "AS IS" BASIS,
|
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 | * See the License for the specific language governing permissions and
|
14 | * limitations under the License.
|
15 | */
|
16 |
|
17 | import {onBFCacheRestore} from './lib/bfcache.js';
|
18 | import {bindReporter} from './lib/bindReporter.js';
|
19 | import {doubleRAF} from './lib/doubleRAF.js';
|
20 | import {getActivationStart} from './lib/getActivationStart.js';
|
21 | import {getVisibilityWatcher} from './lib/getVisibilityWatcher.js';
|
22 | import {initMetric} from './lib/initMetric.js';
|
23 | import {observe} from './lib/observe.js';
|
24 | import {onHidden} from './lib/onHidden.js';
|
25 | import {runOnce} from './lib/runOnce.js';
|
26 | import {whenActivated} from './lib/whenActivated.js';
|
27 | import {whenIdle} from './lib/whenIdle.js';
|
28 | import {LCPMetric, MetricRatingThresholds, ReportOpts} from './types.js';
|
29 |
|
30 | /** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */
|
31 | export const LCPThresholds: MetricRatingThresholds = [2500, 4000];
|
32 |
|
33 | const reportedMetricIDs: Record<string, boolean> = {};
|
34 |
|
35 | /**
|
36 | * Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and
|
37 | * calls the `callback` function once the value is ready (along with the
|
38 | * relevant `largest-contentful-paint` performance entry used to determine the
|
39 | * value). The reported value is a `DOMHighResTimeStamp`.
|
40 | *
|
41 | * If the `reportAllChanges` configuration option is set to `true`, the
|
42 | * `callback` function will be called any time a new `largest-contentful-paint`
|
43 | * performance entry is dispatched, or once the final value of the metric has
|
44 | * been determined.
|
45 | */
|
46 | export const onLCP = (
|
47 | onReport: (metric: LCPMetric) => void,
|
48 | opts?: ReportOpts,
|
49 | ) => {
|
50 | // Set defaults
|
51 | opts = opts || {};
|
52 |
|
53 | whenActivated(() => {
|
54 | const visibilityWatcher = getVisibilityWatcher();
|
55 | let metric = initMetric('LCP');
|
56 | let report: ReturnType<typeof bindReporter>;
|
57 |
|
58 | const handleEntries = (entries: LCPMetric['entries']) => {
|
59 | // If reportAllChanges is set then call this function for each entry,
|
60 | // otherwise only consider the last one.
|
61 | if (!opts!.reportAllChanges) {
|
62 | entries = entries.slice(-1);
|
63 | }
|
64 |
|
65 | entries.forEach((entry) => {
|
66 | // Only report if the page wasn't hidden prior to LCP.
|
67 | if (entry.startTime < visibilityWatcher.firstHiddenTime) {
|
68 | // The startTime attribute returns the value of the renderTime if it is
|
69 | // not 0, and the value of the loadTime otherwise. The activationStart
|
70 | // reference is used because LCP should be relative to page activation
|
71 | // rather than navigation start if the page was prerendered. But in cases
|
72 | // where `activationStart` occurs after the LCP, this time should be
|
73 | // clamped at 0.
|
74 | metric.value = Math.max(entry.startTime - getActivationStart(), 0);
|
75 | metric.entries = [entry];
|
76 | report();
|
77 | }
|
78 | });
|
79 | };
|
80 |
|
81 | const po = observe('largest-contentful-paint', handleEntries);
|
82 |
|
83 | if (po) {
|
84 | report = bindReporter(
|
85 | onReport,
|
86 | metric,
|
87 | LCPThresholds,
|
88 | opts!.reportAllChanges,
|
89 | );
|
90 |
|
91 | const stopListening = runOnce(() => {
|
92 | if (!reportedMetricIDs[metric.id]) {
|
93 | handleEntries(po!.takeRecords() as LCPMetric['entries']);
|
94 | po!.disconnect();
|
95 | reportedMetricIDs[metric.id] = true;
|
96 | report(true);
|
97 | }
|
98 | });
|
99 |
|
100 | // Stop listening after input. Note: while scrolling is an input that
|
101 | // stops LCP observation, it's unreliable since it can be programmatically
|
102 | // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75
|
103 | ['keydown', 'click'].forEach((type) => {
|
104 | // Wrap in a setTimeout so the callback is run in a separate task
|
105 | // to avoid extending the keyboard/click handler to reduce INP impact
|
106 | // https://github.com/GoogleChrome/web-vitals/issues/383
|
107 | addEventListener(type, () => whenIdle(stopListening), true);
|
108 | });
|
109 |
|
110 | onHidden(stopListening);
|
111 |
|
112 | // Only report after a bfcache restore if the `PerformanceObserver`
|
113 | // successfully registered.
|
114 | onBFCacheRestore((event) => {
|
115 | metric = initMetric('LCP');
|
116 | report = bindReporter(
|
117 | onReport,
|
118 | metric,
|
119 | LCPThresholds,
|
120 | opts!.reportAllChanges,
|
121 | );
|
122 |
|
123 | doubleRAF(() => {
|
124 | metric.value = performance.now() - event.timeStamp;
|
125 | reportedMetricIDs[metric.id] = true;
|
126 | report(true);
|
127 | });
|
128 | });
|
129 | }
|
130 | });
|
131 | };
|