UNPKG

2.39 kBPlain TextView Raw
1/*
2 * Copyright 2022 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 {getBFCacheRestoreTime} from '../lib/bfcache.js';
18import {getLoadState} from '../lib/getLoadState.js';
19import {getNavigationEntry} from '../lib/getNavigationEntry.js';
20import {onFCP as unattributedOnFCP} from '../onFCP.js';
21import {
22 FCPMetric,
23 FCPMetricWithAttribution,
24 FCPReportCallback,
25 FCPReportCallbackWithAttribution,
26 ReportOpts,
27} from '../types.js';
28
29const attributeFCP = (metric: FCPMetric): void => {
30 if (metric.entries.length) {
31 const navigationEntry = getNavigationEntry();
32 const fcpEntry = metric.entries[metric.entries.length - 1];
33
34 if (navigationEntry) {
35 const activationStart = navigationEntry.activationStart || 0;
36 const ttfb = Math.max(0, navigationEntry.responseStart - activationStart);
37
38 (metric as FCPMetricWithAttribution).attribution = {
39 timeToFirstByte: ttfb,
40 firstByteToFCP: metric.value - ttfb,
41 loadState: getLoadState(metric.entries[0].startTime),
42 navigationEntry,
43 fcpEntry,
44 };
45 return;
46 }
47 }
48 // Set an empty object if no other attribution has been set.
49 (metric as FCPMetricWithAttribution).attribution = {
50 timeToFirstByte: 0,
51 firstByteToFCP: metric.value,
52 loadState: getLoadState(getBFCacheRestoreTime()),
53 };
54};
55
56/**
57 * Calculates the [FCP](https://web.dev/fcp/) value for the current page and
58 * calls the `callback` function once the value is ready, along with the
59 * relevant `paint` performance entry used to determine the value. The reported
60 * value is a `DOMHighResTimeStamp`.
61 */
62export const onFCP = (
63 onReport: FCPReportCallbackWithAttribution,
64 opts?: ReportOpts
65) => {
66 unattributedOnFCP(
67 ((metric: FCPMetricWithAttribution) => {
68 attributeFCP(metric);
69 onReport(metric);
70 }) as FCPReportCallback,
71 opts
72 );
73};