UNPKG

2.65 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 { bindReporter } from './lib/bindReporter.js';
17import { finalMetrics } from './lib/finalMetrics.js';
18import { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';
19import { initMetric } from './lib/initMetric.js';
20import { observe } from './lib/observe.js';
21import { onBFCacheRestore } from './lib/onBFCacheRestore.js';
22export const getFCP = (onReport, reportAllChanges) => {
23 const visibilityWatcher = getVisibilityWatcher();
24 let metric = initMetric('FCP');
25 let report;
26 const entryHandler = (entry) => {
27 if (entry.name === 'first-contentful-paint') {
28 if (po) {
29 po.disconnect();
30 }
31 // Only report if the page wasn't hidden prior to the first paint.
32 if (entry.startTime < visibilityWatcher.firstHiddenTime) {
33 metric.value = entry.startTime;
34 metric.entries.push(entry);
35 finalMetrics.add(metric);
36 report();
37 }
38 }
39 };
40 // TODO(philipwalton): remove the use of `fcpEntry` once this bug is fixed.
41 // https://bugs.webkit.org/show_bug.cgi?id=225305
42 // Also, the check for `getEntriesByName` is needed to support Opera:
43 // https://github.com/GoogleChrome/web-vitals/issues/159
44 const fcpEntry = performance.getEntriesByName &&
45 performance.getEntriesByName('first-contentful-paint')[0];
46 const po = fcpEntry ? null : observe('paint', entryHandler);
47 if (fcpEntry || po) {
48 report = bindReporter(onReport, metric, reportAllChanges);
49 if (fcpEntry) {
50 entryHandler(fcpEntry);
51 }
52 onBFCacheRestore((event) => {
53 metric = initMetric('FCP');
54 report = bindReporter(onReport, metric, reportAllChanges);
55 requestAnimationFrame(() => {
56 requestAnimationFrame(() => {
57 metric.value = performance.now() - event.timeStamp;
58 finalMetrics.add(metric);
59 report();
60 });
61 });
62 });
63 }
64};