getFCP.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 { finalMetrics } from './lib/finalMetrics.js';
  18. import { getFirstHidden } from './lib/getFirstHidden.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 firstHidden = getFirstHidden();
  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 < firstHidden.timeStamp) {
  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. const fcpEntry = performance.getEntriesByName('first-contentful-paint')[0];
  43. const po = fcpEntry ? null : observe('paint', entryHandler);
  44. if (fcpEntry || po) {
  45. report = bindReporter(onReport, metric, reportAllChanges);
  46. if (fcpEntry) {
  47. entryHandler(fcpEntry);
  48. }
  49. onBFCacheRestore((event) => {
  50. metric = initMetric('FCP');
  51. report = bindReporter(onReport, metric, reportAllChanges);
  52. requestAnimationFrame(() => {
  53. requestAnimationFrame(() => {
  54. metric.value = performance.now() - event.timeStamp;
  55. finalMetrics.add(metric);
  56. report();
  57. });
  58. });
  59. });
  60. }
  61. };