1

I'm trying to use GTM to send data from webVitals to google analytics.

Using this package: https://github.com/GoogleChrome/web-vitals#load-web-vitals-from-a-cdn

<script defer src="https://unpkg.com/web-vitals@1.1.0/dist/web-vitals.umd.js"></script>
<script>
function sendToGoogleAnalytics ({name, delta, id}) {
  // Assumes the global `gtag()` function exists, see:
  // https://developers.google.com/analytics/devguides/collection/gtagjs
  gtag('event', name, {
    event_category: 'Web Vitals',
    // The `id` value will be unique to the current page load. When sending
    // multiple values from the same page (e.g. for CLS), Google Analytics can
    // compute a total by grouping on this ID (note: requires `eventLabel` to
    // be a dimension in your report).
    event_label: id,
    // Google Analytics metrics must be integers, so the value is rounded.
    // For CLS the value is first multiplied by 1000 for greater precision
    // (note: increase the multiplier for greater precision if needed).
    value: Math.round(name === 'CLS' ? delta * 1000 : delta),
    // Use a non-interaction event to avoid affecting bounce rate.
    non_interaction: true,
  });
}

  addEventListener('DOMContentLoaded', function() {
      webVitals.getCLS(sendToGoogleAnalytics);
      webVitals.getFID(sendToGoogleAnalytics);
      webVitals.getLCP(sendToGoogleAnalytics);
   });
 </script>

GTM is complaining: Error at line 3, character 38: This language feature is only supported for ECMASCRIPT6 mode or better: object destructuring.

I thought the issue was with the function call. I tried to modify the function to:

var sendToGoogleAnalytics = function({name, delta, id}){...

Seems that was not the issue. Can someone point out what the linter does not like?

DDulla
  • 659
  • 9
  • 20

2 Answers2

1

You need to use a variable name as parameter and then access the attributes referenceing that variable name.

function sendToGoogleAnalytics (data) {
...
gtag('event', data.name, {
...
Benjamin
  • 1,067
  • 20
  • 30
0

If you're measuring Web Vitals in GTM, I'd recommend the approach outlined by Simo Ahava here: https://www.simoahava.com/analytics/track-core-web-vitals-in-ga4-with-google-tag-manager/

He's written a custom template for the code you referenced above, so you won't have to worry about how to install it.

Philip Walton
  • 29,693
  • 16
  • 60
  • 84