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 {initMetric} from './lib/initMetric.js';
|
19 | import {observe} from './lib/observe.js';
|
20 | import {bindReporter} from './lib/bindReporter.js';
|
21 | import {doubleRAF} from './lib/doubleRAF.js';
|
22 | import {onHidden} from './lib/onHidden.js';
|
23 | import {runOnce} from './lib/runOnce.js';
|
24 | import {onFCP} from './onFCP.js';
|
25 | import {CLSMetric, MetricRatingThresholds, ReportOpts} from './types.js';
|
26 |
|
27 | /** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */
|
28 | export const CLSThresholds: MetricRatingThresholds = [0.1, 0.25];
|
29 |
|
30 | /**
|
31 | * Calculates the [CLS](https://web.dev/articles/cls) value for the current page and
|
32 | * calls the `callback` function once the value is ready to be reported, along
|
33 | * with all `layout-shift` performance entries that were used in the metric
|
34 | * value calculation. The reported value is a `double` (corresponding to a
|
35 | * [layout shift score](https://web.dev/articles/cls#layout_shift_score)).
|
36 | *
|
37 | * If the `reportAllChanges` configuration option is set to `true`, the
|
38 | * `callback` function will be called as soon as the value is initially
|
39 | * determined as well as any time the value changes throughout the page
|
40 | * lifespan.
|
41 | *
|
42 | * _**Important:** CLS should be continually monitored for changes throughout
|
43 | * the entire lifespan of a page—including if the user returns to the page after
|
44 | * it's been hidden/backgrounded. However, since browsers often [will not fire
|
45 | * additional callbacks once the user has backgrounded a
|
46 | * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),
|
47 | * `callback` is always called when the page's visibility state changes to
|
48 | * hidden. As a result, the `callback` function might be called multiple times
|
49 | * during the same page load._
|
50 | */
|
51 | export const onCLS = (
|
52 | onReport: (metric: CLSMetric) => void,
|
53 | opts?: ReportOpts,
|
54 | ) => {
|
55 | // Set defaults
|
56 | opts = opts || {};
|
57 |
|
58 | // Start monitoring FCP so we can only report CLS if FCP is also reported.
|
59 | // Note: this is done to match the current behavior of CrUX.
|
60 | onFCP(
|
61 | runOnce(() => {
|
62 | let metric = initMetric('CLS', 0);
|
63 | let report: ReturnType<typeof bindReporter>;
|
64 |
|
65 | let sessionValue = 0;
|
66 | let sessionEntries: LayoutShift[] = [];
|
67 |
|
68 | const handleEntries = (entries: LayoutShift[]) => {
|
69 | entries.forEach((entry) => {
|
70 | // Only count layout shifts without recent user input.
|
71 | if (!entry.hadRecentInput) {
|
72 | const firstSessionEntry = sessionEntries[0];
|
73 | const lastSessionEntry = sessionEntries[sessionEntries.length - 1];
|
74 |
|
75 | // If the entry occurred less than 1 second after the previous entry
|
76 | // and less than 5 seconds after the first entry in the session,
|
77 | // include the entry in the current session. Otherwise, start a new
|
78 | // session.
|
79 | if (
|
80 | sessionValue &&
|
81 | entry.startTime - lastSessionEntry.startTime < 1000 &&
|
82 | entry.startTime - firstSessionEntry.startTime < 5000
|
83 | ) {
|
84 | sessionValue += entry.value;
|
85 | sessionEntries.push(entry);
|
86 | } else {
|
87 | sessionValue = entry.value;
|
88 | sessionEntries = [entry];
|
89 | }
|
90 | }
|
91 | });
|
92 |
|
93 | // If the current session value is larger than the current CLS value,
|
94 | // update CLS and the entries contributing to it.
|
95 | if (sessionValue > metric.value) {
|
96 | metric.value = sessionValue;
|
97 | metric.entries = sessionEntries;
|
98 | report();
|
99 | }
|
100 | };
|
101 |
|
102 | const po = observe('layout-shift', handleEntries);
|
103 | if (po) {
|
104 | report = bindReporter(
|
105 | onReport,
|
106 | metric,
|
107 | CLSThresholds,
|
108 | opts!.reportAllChanges,
|
109 | );
|
110 |
|
111 | onHidden(() => {
|
112 | handleEntries(po.takeRecords() as CLSMetric['entries']);
|
113 | report(true);
|
114 | });
|
115 |
|
116 | // Only report after a bfcache restore if the `PerformanceObserver`
|
117 | // successfully registered.
|
118 | onBFCacheRestore(() => {
|
119 | sessionValue = 0;
|
120 | metric = initMetric('CLS', 0);
|
121 | report = bindReporter(
|
122 | onReport,
|
123 | metric,
|
124 | CLSThresholds,
|
125 | opts!.reportAllChanges,
|
126 | );
|
127 |
|
128 | doubleRAF(() => report());
|
129 | });
|
130 |
|
131 | // Queue a task to report (if nothing else triggers a report first).
|
132 | // This allows CLS to be reported as soon as FCP fires when
|
133 | // `reportAllChanges` is true.
|
134 | setTimeout(report, 0);
|
135 | }
|
136 | }),
|
137 | );
|
138 | };
|