From c134430d2d348aa64b62d936ff1c7255d0ba3c4d Mon Sep 17 00:00:00 2001 From: laradevitt Date: Tue, 8 Jun 2021 12:21:20 -0600 Subject: [PATCH] Fixes #3 CLS event values sent to GA aren't useful. --- README.md | 7 +++++++ src/web-vitals.js | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d231b4..ea55ea3 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,13 @@ or } ``` +## Important note + +Because Google Analytics metrics must be integers, all event values are rounded +before being sent. To be meaningful, CLS values are also multiplied by 1000. +This is the approach recommended in the [Web Vitals documentation](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics) and will be +important to keep in mind when preparing your reports. + --- Plugin based on [`nuxt-vitals`](https://github.com/daliborgogic/nuxt-vitals). diff --git a/src/web-vitals.js b/src/web-vitals.js index 158c597..89fe11e 100644 --- a/src/web-vitals.js +++ b/src/web-vitals.js @@ -35,7 +35,8 @@ function sendToAnalytics(metric, options) { ea: name, el: id, // Google Analytics metrics must be integers, so the value is rounded. - ev: parseInt(delta), + // For CLS the value is first multiplied by 1000 for greater precision. + ev: Math.round(name === 'CLS' ? delta * 1000 : delta), dl: location.href, dp: location.pathname, ni: true, @@ -52,6 +53,7 @@ function sendToAnalytics(metric, options) { const url = encode(obj); if (options.debug) { + onDebug(name + " original value", delta); onDebug(name, JSON.stringify(obj, null, 2)); onDebug(name + " URL", url); }