Last active
August 28, 2020 21:55
-
-
Save adamsilverstein/c1734fd50c4e1f28c7428d1fc7ab2870 to your computer and use it in GitHub Desktop.
Measure Web Vitals in Analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Measure Web Vitals in Analytics | |
* | |
* @copyright 2020 Google LLC | |
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 | |
* | |
* @wordpress-plugin | |
* Plugin Name: Measure Vitals | |
* Description: Measure Web Vitals in Analytics | |
* Version: 1.0.0 | |
* Author: Google | |
* Author URI: https://opensource.google.com | |
* License: Apache License 2.0 | |
* License URI: https://www.apache.org/licenses/LICENSE-2.0 | |
*/ | |
add_action( 'wp_head', function() { | |
?> | |
<!-- Load `web-vitals` using a classic script that sets the global `webVitals` object. --> | |
<script defer src="https://unpkg.com/web-vitals@0.2.3/dist/web-vitals.es5.umd.min.js"></script> | |
<script> | |
addEventListener('DOMContentLoaded', function() { | |
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, | |
}); | |
} | |
webVitals.getCLS(sendToGoogleAnalytics); | |
webVitals.getFID(sendToGoogleAnalytics); | |
webVitals.getLCP(sendToGoogleAnalytics); | |
}); | |
</script> | |
<?php | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment