AMP
  • websites

Tracking Core Web Vitals

Introduction

AMP developers can measure Core Web Vitals metrics through the amp-analytics component. Use variable substitution to add these metrics to any outgoing requests made by amp-analytics.

Learn more about amp-analytics in our guide Analytics: the basics.

Setup

Import the amp-analytics component in the header.

<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>

Using amp-analytics to track Core Web Vitals

The amp-analytics component provides the following macros:

These macros can attach to any triggers and resolve asynchronously.

<amp-analytics>
  <script type="application/json">
    {
      "requests": {
        "event": "https://amp.dev/documentation/examples/advertising-analytics/tracking_core_web_vitals/ping?user=&account=ampdev&event=${eventId}",
        "pageview": "${event}&lcp=${lcp}&fid=${fid}&cls=${cls}"
      },
      "triggers": {
        "trackPageview": {
          "on": "visible",
          "request": "pageview",
          "vars": {
            "eventId": "pageview",
            "lcp": "${largestContentfulPaint}",
            "cls": "${cumulativeLayoutShift}",
            "fid": "${firstInputDelay}"
          }
        }
      }
    }
  </script>
</amp-analytics>

Tracking Core Web Vitals in AMP using Google Analytics

Analytics must be configured in the body. Here we use Google Analytics to track pageviews and use the extraUrlParams feature to append the Core Web Vitals to the request URL.

<amp-analytics type="googleanalytics">
  <script type="application/json">
    {
      "vars": {
         "gtag_id": "UA-XXXXXXXXX-X",
         "config": {
           "UA-XXXXXXXXX-X": {
              "groups": "default"
           }
         }
      },
      "triggers": {
        "default pageview": {
          "on": "visible",
          "request": "pageview",
          "vars": {
            "title": "{{title}}"
          },
          "extraUrlParams": {
            "lcp": "${largestContentfulPaint}",
            "cls": "${cumulativeLayoutShift}",
            "fid": "${firstInputDelay}"
          }
        }
      }
    }
  </script>
</amp-analytics>
Need further explanation?

If the explanations on this page don't cover all of your questions feel free to reach out to other AMP users to discuss your exact use case.

Go to Stack Overflow
An unexplained feature?

The AMP project strongly encourages your participation and contributions! We hope you'll become an ongoing participant in our open source community but we also welcome one-off contributions for the issues you're particularly passionate about.

Edit sample on GitHub