UNPKG

2.06 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 {getFirstHidden} from './lib/getFirstHidden.js';
20import {initMetric} from './lib/initMetric.js';
21import {observe} from './lib/observe.js';
22import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
23import {ReportHandler} from './types.js';
24
25
26export const getFCP = (onReport: ReportHandler, reportAllChanges?: boolean) => {
27 const firstHidden = getFirstHidden();
28 let metric = initMetric('FCP');
29 let report: ReturnType<typeof bindReporter>;
30
31 const entryHandler = (entry: PerformanceEntry) => {
32 if (entry.name === 'first-contentful-paint') {
33 if (po) {
34 po.disconnect();
35 }
36
37 // Only report if the page wasn't hidden prior to the first paint.
38 if (entry.startTime < firstHidden.timeStamp) {
39 metric.value = entry.startTime;
40 metric.entries.push(entry);
41 finalMetrics.add(metric);
42 report();
43 }
44 }
45 };
46
47 const po = observe('paint', entryHandler);
48 if (po) {
49 report = bindReporter(onReport, metric, reportAllChanges);
50
51 onBFCacheRestore((event) => {
52 metric = initMetric('FCP');
53 report = bindReporter(onReport, metric, reportAllChanges);
54 requestAnimationFrame(() => {
55 requestAnimationFrame(() => {
56 metric.value = performance.now() - event.timeStamp;
57 finalMetrics.add(metric);
58 report();
59 });
60 });
61 });
62 }
63};