getFCP.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. import { bindReporter } from './lib/bindReporter.js';
  17. import { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';
  18. import { initMetric } from './lib/initMetric.js';
  19. import { observe } from './lib/observe.js';
  20. import { onBFCacheRestore } from './lib/onBFCacheRestore.js';
  21. export const getFCP = (onReport, reportAllChanges) => {
  22. const visibilityWatcher = getVisibilityWatcher();
  23. let metric = initMetric('FCP');
  24. let report;
  25. const entryHandler = (entry) => {
  26. if (entry.name === 'first-contentful-paint') {
  27. if (po) {
  28. po.disconnect();
  29. }
  30. // Only report if the page wasn't hidden prior to the first paint.
  31. if (entry.startTime < visibilityWatcher.firstHiddenTime) {
  32. metric.value = entry.startTime;
  33. metric.entries.push(entry);
  34. report(true);
  35. }
  36. }
  37. };
  38. // TODO(philipwalton): remove the use of `fcpEntry` once this bug is fixed.
  39. // https://bugs.webkit.org/show_bug.cgi?id=225305
  40. // The check for `getEntriesByName` is needed to support Opera:
  41. // https://github.com/GoogleChrome/web-vitals/issues/159
  42. // The check for `window.performance` is needed to support Opera mini:
  43. // https://github.com/GoogleChrome/web-vitals/issues/185
  44. const fcpEntry = window.performance && 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. report(true);
  59. });
  60. });
  61. });
  62. }
  63. };