Skip to content

Instantly share code, notes, and snippets.

@anniesullie
Last active May 14, 2021 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anniesullie/12fb38e4c5b8c9bc36818c8cc337491e to your computer and use it in GitHub Desktop.
Save anniesullie/12fb38e4c5b8c9bc36818c8cc337491e to your computer and use it in GitHub Desktop.
"Step Through" CLS
/**
* A bookmarklet for viewing shifted elements while debugging
* Cumulative Layout Shift (web.dev/cls). Works in Chrome 84+
* Shows the previous position of shifted elements in yellow,
* and the new position in red. Adds in a `debugger;` statement
* each timet the performance observer is notified of a layout
* shift, allowing the user to attempt to "step through" the
* shifts by pausing on each one in the devtools debugger.
* Note that the shifts have already happened at this point.
*
* To install:
* 1. Copy the code starting from the line beginning `javascript:`
* 2. Add a new bookmark in Chrome, and paste the code in as the URL.
**/
javascript:(function(){
try {
let cls = 0;
const canvas = document.createElement('canvas');
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = 'absolute';
canvas.style.left = 0;
canvas.style.top = 0;
canvas.style.zIndex = 100000;
canvas.style.pointerEvents = 'none';
document.body.appendChild(canvas);
const context = canvas.getContext('2d');
const po = new PerformanceObserver((list) => {
debugger;
canvas.style.transition = 'opacity 0s';
canvas.style.opacity = 1;
context.clearRect(0, 0, canvas.width, canvas.height);
for (const entry of list.getEntries()) {
cls += entry.value;
for (const source of entry.sources) {
context.strokeStyle = 'yellow';
context.strokeRect(source.previousRect.x,
source.previousRect.y,
source.previousRect.width,
source.previousRect.height);
context.strokeStyle = 'red';
context.strokeRect(source.currentRect.x,
source.currentRect.y,
source.currentRect.width,
source.currentRect.height);
console.log(source);
}
setTimeout(function() {
canvas.style.transition = 'opacity 2s';
canvas.style.opacity = 0;
}, 100);
}
console.log('CLS is now: ', cls);
});
po.observe({type: 'layout-shift', buffered: true});
} catch (e) {
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment