getFID.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. import { onHidden } from './lib/onHidden.js';
  22. import { firstInputPolyfill, resetFirstInputPolyfill } from './lib/polyfills/firstInputPolyfill.js';
  23. export const getFID = (onReport, reportAllChanges) => {
  24. const visibilityWatcher = getVisibilityWatcher();
  25. let metric = initMetric('FID');
  26. let report;
  27. const entryHandler = (entry) => {
  28. // Only report if the page wasn't hidden prior to the first input.
  29. if (entry.startTime < visibilityWatcher.firstHiddenTime) {
  30. metric.value = entry.processingStart - entry.startTime;
  31. metric.entries.push(entry);
  32. report(true);
  33. }
  34. };
  35. const po = observe('first-input', entryHandler);
  36. report = bindReporter(onReport, metric, reportAllChanges);
  37. if (po) {
  38. onHidden(() => {
  39. po.takeRecords().map(entryHandler);
  40. po.disconnect();
  41. }, true);
  42. }
  43. if (window.__WEB_VITALS_POLYFILL__) {
  44. // Prefer the native implementation if available,
  45. if (!po) {
  46. window.webVitals.firstInputPolyfill(entryHandler);
  47. }
  48. onBFCacheRestore(() => {
  49. metric = initMetric('FID');
  50. report = bindReporter(onReport, metric, reportAllChanges);
  51. window.webVitals.resetFirstInputPolyfill();
  52. window.webVitals.firstInputPolyfill(entryHandler);
  53. });
  54. }
  55. else {
  56. // Only monitor bfcache restores if the browser supports FID natively.
  57. if (po) {
  58. onBFCacheRestore(() => {
  59. metric = initMetric('FID');
  60. report = bindReporter(onReport, metric, reportAllChanges);
  61. resetFirstInputPolyfill();
  62. firstInputPolyfill(entryHandler);
  63. });
  64. }
  65. }
  66. };