Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Web Vital's Basic
<!-- Add to Header -->
<script src="https://unpkg.com/web-vitals@0.2.2/dist/web-vitals.es5.umd.min.js"></script>
<!-- Add to Footer -->
<script>
function sendToGoogleAnalytics({name, delta, id}) {
// Assumes the global `ga()` function exists, see:
// https://developers.google.com/analytics/devguides/collection/analyticsjs
ga('send', 'event', {
eventCategory: 'Web Vitals',
eventAction: 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).
eventValue: 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).
eventLabel: id,
// Use a non-interaction event to avoid affecting bounce rate.
nonInteraction: true,
});
}
addEventListener('DOMContentLoaded', function() {
webVitals.getCLS(sendToGoogleAnalytics);
webVitals.getFID(sendToGoogleAnalytics);
webVitals.getLCP(sendToGoogleAnalytics);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.