Skip to content

Instantly share code, notes, and snippets.

@wpsmith
Created January 17, 2021 14:37
Show Gist options
  • Save wpsmith/12937751a0f6125ea7398990b2543d14 to your computer and use it in GitHub Desktop.
Save wpsmith/12937751a0f6125ea7398990b2543d14 to your computer and use it in GitHub Desktop.
WordPress: PHP/JS For detecting CLS
<?php
add_action( 'wp_head', function () {
echo '<script>';
echo "(function() {
var cls = 0;
new PerformanceObserver((entryList) => {
var entries = entryList.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (!entry.hadRecentInput) {
cls += entry.value;
console.log('Current CLS value:', cls, entry);
}
}
}).observe({type: 'layout-shift', buffered: true});
})();
";
echo '</script>';
}, 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment