How we measure Core Web Vitals Part two — starting in the browser with web-vitals library and the dataLayer

Kevin McCarthy
3 min readMar 16, 2021

TL:DR we started by adding the core-web-vitals library and then push the data to the data layer.

In our previous post we looked at the high level picture of all the steps in our measurement. In this post we’ll look at the first step, capturing the values in the browser as they happen.

web-vitals library

We started by adding the web-vitals javascript library. We did this by running

yarn add web-vitals 

but they have a ton of different options for how to include the library in their github repo.

This allows us to measure the core web vitals LCP, CLS, FID and also TTFB and FCP.

In our codebase

The below link is the version of the code we’ve copied from google as we use Google Tag Manager to handle our events to Google Analytics

Here is what our file looks like

// CoreWebVitals.jsimport { getCLS, getFID, getLCP, getFCP, getTTFB } from 'web-vitals';import { pushToDataLayer } from './PushToDataLayer'function sendCoreWebVitalsToGTM({name, delta, id}) {  const customEventProperties = {    'webVitals': {      event_category: 'Web Vitals',      event_action: name,      event_value: Math.round(name === 'CLS' ? delta * 1000 : delta),      event_label: id    }  }  pushToDataLayer('web-vitals', customEventProperties)}
function pushToDataLayer(eventName, customEventProperties) { const simpleEvent = { 'event': eventName } if (customEventProperties) { window.dataLayer.push({ ...simpleEvent, ...customEventProperties }); return; } window.dataLayer.push(simpleEvent);}export function getCoreWebVitals() { getCLS(sendCoreWebVitalsToGTM); getFID(sendCoreWebVitalsToGTM); getLCP(sendCoreWebVitalsToGTM); getFCP(sendCoreWebVitalsToGTM); getTTFB(sendCoreWebVitalsToGTM);}// somewhere else in our codeimport { getCoreWebVitals } from '../analytics/CoreWebVitals'document.addEventListener('DOMContentLoaded', () => {
getCoreWebVitals()
}

web-vitals in the dataLayer

This will now add events to the dataLayer which you can see in the browser by opening up the console (right-click anywhere on the screen and choose Inspect Element and then choose console).

Then type in window.dataLayer this will show all dataLayer objects including any web-vitals events.

This event is an LCP event and has a value of 1094 (1.1s). The event_label is unique to each page load so all events in this dataLayer should have the same event_label.

Not super consistent

These events do not fire on every page load and its rare to see every event captured. I’m not sure why this is but have just taken it as part of the difficulties of dealing with the browsers internals. Google’s web-vitals library uses the PerformanceEntry API I believe to get these values.

--

--