From b7a7e3e202f8dc4de97994cdf36ece95075082c4 Mon Sep 17 00:00:00 2001 From: ekremney Date: Wed, 28 Feb 2024 16:16:32 +0100 Subject: [PATCH] fix(cwv): report metrics eagerly --- src/index.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index dce9615..6f219a2 100644 --- a/src/index.js +++ b/src/index.js @@ -91,14 +91,19 @@ sampleRUM.drain('cwv', (() => { data.cwv[measurement.name] = measurement.value; sampleRUM('cwv', data); }; + + const featureToggle = () => window.location.hostname === 'blog.adobe.com'; + const isEager = (metric) => ['CLS', 'LCP'].includes(metric); + // When loading `web-vitals` using a classic script, all the public // methods can be found on the `webVitals` global namespace. - ['CLS', 'FID', 'LCP', 'INP', 'TTFB'] - .map((metric) => window.webVitals[`get${metric}`]) - .filter((metric) => typeof metric === 'function') - .forEach((invokeMetric) => { - invokeMetric(storeCWV); - }); + ['FID', 'INP', 'TTFB', 'CLS', 'LCP'].forEach((metric) => { + const metricFn = window.webVitals[`on${metric}`]; + if (typeof metricFn === 'function') { + const opts = isEager(metric) ? { reportAllChanges: featureToggle() } : undefined; + metricFn(storeCWV, opts); + } + }); }; document.head.appendChild(script); }));