UNPKG

1.9 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 {initMetric} from './lib/initMetric.js';
18import {observe, PerformanceEntryHandler} from './lib/observe.js';
19import {onHidden} from './lib/onHidden.js';
20import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
21import {bindReporter} from './lib/bindReporter.js';
22import {ReportHandler} from './types.js';
23
24
25// https://wicg.github.io/layout-instability/#sec-layout-shift
26interface LayoutShift extends PerformanceEntry {
27 value: number;
28 hadRecentInput: boolean;
29}
30
31export const getCLS = (onReport: ReportHandler, reportAllChanges?: boolean) => {
32 let metric = initMetric('CLS', 0);
33 let report: ReturnType<typeof bindReporter>;
34
35 const entryHandler = (entry: LayoutShift) => {
36 // Only count layout shifts without recent user input.
37 if (!entry.hadRecentInput) {
38 (metric.value as number) += entry.value;
39 metric.entries.push(entry);
40 report();
41 }
42 };
43
44 const po = observe('layout-shift', entryHandler as PerformanceEntryHandler);
45 if (po) {
46 report = bindReporter(onReport, metric, reportAllChanges);
47
48 onHidden(() => {
49 po.takeRecords().map(entryHandler as PerformanceEntryHandler);
50 report();
51 });
52
53 onBFCacheRestore(() => {
54 metric = initMetric('CLS', 0);
55 report = bindReporter(onReport, metric, reportAllChanges);
56 });
57 }
58};