Google has released Web Vitals, an opinionated browser performance API wrapper to track essential metrics for a healthy site. It will be an evolving user-centric page speed metrics implemented across various Google tools for web developers. Web Vitals is a nudge for website owners to start measuring real user experience, instead of relying on synthetic tests like Lighthouse. Let’s see how to add Web Vitals to a website and start sending data to Google Analytics.

Web Vitals repository

Web Vitals library is written in TypeScript. If you are using TypeScript then you already have some build pipeline setup and can find the Web Vitals package on NPM. Pure JavaScript path is a bit more tricky and worth covering in more detail. To get a JavaScript file you will need to checkout Web Vitals github repo, “npm install” dependencies and build from source by running “npm run build”. Of course, NodeJS should already be installed on your computer. After building from source, you will find the JS library version in “dist/web-vitals.min.js”.

Adding Web Vitals to your website

One way to implement the code needed for Web Vitals is to create a new file, lets call it “main.js”. This file will import Web Vitals and subscribe to main metrics. The main.js file is then loaded with a script tag which has type=”module” attribute. The minified version of Web Vitals JS file is a JS module. If you simply try to load it with a regular script tag, you will get an Unexpected token 'export' exception in the browser. Since main.js uses an import statement, it is also a JS module and needs type=”module” attribute.

index.html

<script defer src="/main.js" type="module"></script>

main.js

import { getCLS, getFID, getLCP } from "/web-vitals.min.js";
 
function sendToGoogleAnalytics({ name, delta, id }) {
   gtag('event', name, {
       event_category: 'Web Vitals',
       value: Math.round(name === 'CLS' ? delta * 1000 : delta),
       event_label: id,
       non_interaction: true,
   });
}
 
getCLS(sendToGoogleAnalytics);
getFID(sendToGoogleAnalytics);
getLCP(sendToGoogleAnalytics);

Reporting to Google Analytics

Google Analytics does not have page speed reports out of the box. Web Vitals metrics need to be sent as custom events and new reports can be built with Google Data Studio. Stay tuned for a followup article how to build a Data Studio report using data from Web Vitals.

Next

I will be covering updates to Web Vitals and sharing practical recommendations as I gain more experience using it for monitoring and optimizing MobileRank.co performance. For now, it should be enough to start collecting real life page speed metrics and sending data to Google Analytics for further processing.