UNPKG

2.88 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 {bindReporter} from './lib/bindReporter.js';
18import {finalMetrics} from './lib/finalMetrics.js';
19import {getVisibilityWatcher} from './lib/getVisibilityWatcher.js';
20import {initMetric} from './lib/initMetric.js';
21import {observe, PerformanceEntryHandler} from './lib/observe.js';
22import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
23import {onHidden} from './lib/onHidden.js';
24import {ReportHandler} from './types.js';
25
26
27export const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean) => {
28 const visibilityWatcher = getVisibilityWatcher();
29 let metric = initMetric('LCP');
30 let report: ReturnType<typeof bindReporter>;
31
32 const entryHandler = (entry: PerformanceEntry) => {
33 // The startTime attribute returns the value of the renderTime if it is not 0,
34 // and the value of the loadTime otherwise.
35 const value = entry.startTime;
36
37 // If the page was hidden prior to paint time of the entry,
38 // ignore it and mark the metric as final, otherwise add the entry.
39 if (value < visibilityWatcher.firstHiddenTime) {
40 metric.value = value;
41 metric.entries.push(entry);
42 }
43
44 report();
45 };
46
47 const po = observe('largest-contentful-paint', entryHandler);
48
49 if (po) {
50 report = bindReporter(onReport, metric, reportAllChanges);
51
52 const stopListening = () => {
53 if (!finalMetrics.has(metric)) {
54 po.takeRecords().map(entryHandler as PerformanceEntryHandler);
55 po.disconnect();
56 finalMetrics.add(metric);
57 report();
58 }
59 }
60
61 // Stop listening after input. Note: while scrolling is an input that
62 // stop LCP observation, it's unreliable since it can be programmatically
63 // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75
64 ['keydown', 'click'].forEach((type) => {
65 addEventListener(type, stopListening, {once: true, capture: true});
66 });
67
68 onHidden(stopListening, true);
69
70 onBFCacheRestore((event) => {
71 metric = initMetric('LCP');
72 report = bindReporter(onReport, metric, reportAllChanges);
73 requestAnimationFrame(() => {
74 requestAnimationFrame(() => {
75 metric.value = performance.now() - event.timeStamp;
76 finalMetrics.add(metric);
77 report();
78 });
79 });
80 });
81 }
82};