1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | import { bindReporter } from './lib/bindReporter.js';
|
17 | import { finalMetrics } from './lib/finalMetrics.js';
|
18 | import { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';
|
19 | import { initMetric } from './lib/initMetric.js';
|
20 | import { observe } from './lib/observe.js';
|
21 | import { onBFCacheRestore } from './lib/onBFCacheRestore.js';
|
22 | export 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 |
|
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 |
|
41 |
|
42 |
|
43 |
|
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 | };
|