UNPKG

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