Skip to content

Commit

Permalink
Merge pull request #28 from SimenHansen/google-tag-manger-example
Browse files Browse the repository at this point in the history
Send metrics as Google Tag Manager events
  • Loading branch information
philipwalton authored May 10, 2020
2 parents c933cff + 59dcfa2 commit f2e6fcd
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- [Report only the delta of changes](#report-only-the-delta-of-changes)
- [Send the results to an analytics endpoint](#send-the-results-to-an-analytics-endpoint)
- [Send the results to Google Analytics](#send-the-results-to-google-analytics)
- [Send the results to Google Tag Manager](#send-the-results-to-google-tag-manager)
- [Load `web-vitals` from a CDN](#load-web-vitals-from-a-cdn)
- [API](#api)
- [Types](#types)
Expand Down Expand Up @@ -189,6 +190,33 @@ getFID(sendToGoogleAnalytics);
getLCP(sendToGoogleAnalytics);
```

### Send the results to Google Tag Manager

The following example measures each of the Core Web Vitals metrics and sends them as seperate `dataLayer-events` to be used by Google Tag Manager. With the `web-vitals` trigger you send the metrics to any tag inside your account.

```js
import {getCLS, getFID, getLCP} from 'web-vitals';

function sendToGoogleAnalytics({name, delta, id}) {
// Assumes the global `dataLayer` array exists, see:
// https://developers.google.com/tag-manager/devguide
dataLayer.push({
event: 'web-vitals',
event_category: 'Web Vitals',
event_action: name,
// 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).
event_value: Math.round(name === 'CLS' ? delta * 1000 : delta),
// 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

});
```
### Load `web-vitals` from a CDN
The recommended way to use the `web-vitals` package is to install it from npm and integrate it into your build process. However, if you're not using npm, it's still possible to use `web-vitals` by requesting it from a CDN that serves npm package files.
Expand Down

0 comments on commit f2e6fcd

Please sign in to comment.