Skip to content

Instantly share code, notes, and snippets.

@jaesbit
Created November 23, 2023 16:33
Show Gist options
  • Save jaesbit/8ad14eb45e7610f2985eeaff40e6502a to your computer and use it in GitHub Desktop.
Save jaesbit/8ad14eb45e7610f2985eeaff40e6502a to your computer and use it in GitHub Desktop.
[tampermonkey] CLS logger using PerformanceObserver
// ==UserScript==
// @name Cumulative Layout Shift Measure
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Try to improve your CWV score
// @author @jaesbit
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let CLS = 0;
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.hadRecentInput) { return; } // Ignore shifts after recent input.
CLS += entry.value;
if (entry.value < 0.01) { return; } // Ignore small shifts.
console.log(`[CLS] Layout shift of ${entry.value} at ${entry.startTime} with computed score ${CLS}`);
entry.sources.forEach((source) => {
const element = source.node;
if (element) {
console.log('[CLS] Element causing shift:', element);
}
});
});
}).observe({ type: 'layout-shift', buffered: true });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment