Skip to content

Instantly share code, notes, and snippets.

@felixarntz
Last active February 16, 2023 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixarntz/112c5dcb72ca3af86557550979a5e9dd to your computer and use it in GitHub Desktop.
Save felixarntz/112c5dcb72ca3af86557550979a5e9dd to your computer and use it in GitHub Desktop.
Mini WordPress plugin that uses https://github.com/GoogleChrome/web-vitals to log Core Web Vitals and other key client metrics to the browser console
<?php
/**
* Plugin Name: Web Vitals Logger
* Plugin URI: https://gist.github.com/felixarntz/112c5dcb72ca3af86557550979a5e9dd
* Description: Logs Core Web Vitals and other useful client-side metrics in the browser console.
* Requires at least: 6.1
* Requires PHP: 5.6
* Version: 0.1.0
* Author: Felix Arntz
* Author URI: https://felix-arntz.me
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* Text Domain: web-vitals-logger
*
* @package web-vitals-logger
*/
/**
* Outputs a script to expose Core Web Vitals and other important client metrics in the console.
*
* @see https://github.com/GoogleChrome/web-vitals
*/
function wvl_measure_client_web_vitals() {
$js = 'import {onCLS, onFCP, onFID, onINP, onLCP, onTTFB } from "https://unpkg.com/web-vitals@3?module";';
$js .= 'const printMetric = ( { name, delta } ) => console.log( `Web-Vitals: ${ name }: ${ name === "CLS" ? delta * 1000 : delta }` );';
$js .= 'onCLS(printMetric);';
$js .= 'onFCP(printMetric);';
$js .= 'onFID(printMetric);';
$js .= 'onINP(printMetric);';
$js .= 'onLCP(printMetric);';
$js .= 'onTTFB(printMetric);';
wp_print_inline_script_tag( $js, array( 'type' => 'module' ) );
}
add_action( 'wp_head', 'wvl_measure_client_web_vitals' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment