getCLS.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 {initMetric} from './lib/initMetric.js';
  17. import {observe, PerformanceEntryHandler} from './lib/observe.js';
  18. import {onHidden} from './lib/onHidden.js';
  19. import {onBFCacheRestore} from './lib/onBFCacheRestore.js';
  20. import {bindReporter} from './lib/bindReporter.js';
  21. import {ReportHandler} from './types.js';
  22. // https://wicg.github.io/layout-instability/#sec-layout-shift
  23. interface LayoutShift extends PerformanceEntry {
  24. value: number;
  25. hadRecentInput: boolean;
  26. }
  27. export const getCLS = (onReport: ReportHandler, reportAllChanges?: boolean) => {
  28. let metric = initMetric('CLS', 0);
  29. let report: ReturnType<typeof bindReporter>;
  30. const entryHandler = (entry: LayoutShift) => {
  31. // Only count layout shifts without recent user input.
  32. if (!entry.hadRecentInput) {
  33. (metric.value as number) += entry.value;
  34. metric.entries.push(entry);
  35. report();
  36. }
  37. };
  38. const po = observe('layout-shift', entryHandler as PerformanceEntryHandler);
  39. if (po) {
  40. report = bindReporter(onReport, metric, reportAllChanges);
  41. onHidden(() => {
  42. po.takeRecords().map(entryHandler as PerformanceEntryHandler);
  43. report();
  44. });
  45. onBFCacheRestore(() => {
  46. metric = initMetric('CLS', 0);
  47. report = bindReporter(onReport, metric, reportAllChanges);
  48. });
  49. }
  50. };