UNPKG

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