Measure and report Core Web Vitals with the web-vitals library

1. Before you begin

This codelab teaches you how to measure and report a web page's Core Web Vitals with the web-vitals JavaScript library.

Prerequisites

What you'll do

  • Add the web-vitals library to a web page.
  • Measure the web page's Core Web Vitals.
  • Report the web page's Core Web Vitals.

What you'll need

  • A Chromium-based web browser, such as Google Chrome or Microsoft Edge (For more information about why you need a Chromium-based web browser, see Browser Support.)
  • A text editor of your choice, such as Sublime Text or Visual Studio Code

2. Add the web-vitals library to a web page

First, add the web-vitals library to a web page.

  1. Open a new file in your text editor.
  2. Copy this source code, which creates the web page that you use for this codelab:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Web Vitals Test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
  <p>Text below image</p>
</body>
</html>
  1. Paste the source code into the blank file in your text editor.
  2. Save the file locally as web-vitals-test.html.
  3. Copy this module script, which loads the web-vitals library from a content delivery network.
<script type="module">
  import {getCLS, getFID, getLCP} from 'https://unpkg.com/web-vitals?module';

  getCLS(console.log);
  getFID(console.log);
  getLCP(console.log);
</script>
  1. Paste the module script into the file in your text editor, as you see it in this code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Web Vitals Test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
  <p>Text below image</p>

<script type="module">
  import {getCLS, getFID, getLCP} from 'https://unpkg.com/web-vitals?module';

  getCLS(console.log);
  getFID(console.log);
  getLCP(console.log);
</script>
</body>
</html>
  1. Save the file.

You added the web-vitals library to the web page.

3. Measure the web page's Core Web Vitals

Next, measure the web page's Core Web Vitals.

  1. Open the saved file in your web browser.
  2. Right-click the web page.
  3. Click Inspect to open Google Chrome Developer Tools.

dbf133edad8a425e.png

  1. Click the Console tab > Console settings b5c716ebfacfd86.png .

c9ea29ea2160c2d0.png

  1. Select the Preserve log checkbox to make logs persist when you refresh the web page.

4a608020a6b48385.png

  1. Click the Network tab > Online > Slow 3G to simulate a slow network connection.

7bec83953b1794a0.png

  1. Click the Console tab.
  2. Click anywhere on the web page to force the metrics for Largest Contentful Paint (LCP) and First Input Delay (FID) to print.

25573696ec600a51.png

  1. Click Reload this page acaaa8c0fdd33b1.png to force the metric for Cumulative Layout Shift (CLS) to print.

edd219c1b09598b8.png

  1. Click the Network tab > Online > Fast 3G to simulate a fast network connection.

fa6cee2a7d4a0cf0.png

  1. Click the Console tab.
  2. Click anywhere on the web page to force the metrics for LCP and FID to print again.

49801c70942dde9d.png

  1. Click Reload this page acaaa8c0fdd33b1.png to force the metric for CLS to print again.

dfebb94f9ec2ac10.png

You measured the web page's Core Web Vitals.

4. Optional: Report the web page's Core Web Vitals

Finally, report the web page's Core Web Vitals to Google Analytics.

  1. Copy this code, which sends the Core Web Vitals to Analytics.
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',
    // 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),
    // 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,
    // Use a non-interaction event to avoid affecting bounce rate.
    non_interaction: true,
  });
}

getCLS(sendToGoogleAnalytics);
getFID(sendToGoogleAnalytics);
getLCP(sendToGoogleAnalytics);
  1. Paste the code into the file in your text editor as you see it in this code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Web Vitals Test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <p><img style="max-width: 360px" src="https://placekitten.com/g/3840/2160" alt="Kitten" /></p>
  <p>Text below image</p>

<script type="module">
  import {getCLS, getFID, getLCP} from 'https://unpkg.com/web-vitals?module';

  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',
      // 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),
      // 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,
      // Use a non-interaction event to avoid affecting bounce rate.
      non_interaction: true,
    });
  }

  getCLS(sendToGoogleAnalytics);
  getFID(sendToGoogleAnalytics);
  getLCP(sendToGoogleAnalytics);
</script>
</body>
</html>
  1. Save the file.

You reported the web page's Core Web Vitals.

5. Congratulations

Congratulations! You learned how to measure and report the web page's Core Web Vitals with the web-vitals library.

Learn more