JavaScript debugging for Cumulative Layout Shift (CLS)
Categories:
A. JavaScript PerformanceObserver
You can put the scripts below to observe your all CLS elements
. And you can see the CLS value
and which element
that cause CLS
let cls = 0;
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
// 500 ms input exclusion window
if (!entry.hadRecentInput) {
cls += entry.value;
console.log('Current CLS value:', cls, 'node:', entry.sources[0].node);
// console.log('Current CLS value:', cls, entry);
}
}
// the buffered flag enables observer to access entries from before the observer creation
}).observe({type: 'layout-shift', buffered: true});
The observed result will look like the below.
B. web-vitals Library
You can put the scripts below to observe CLS elements
. And you can see all CLS elements
in the console.
<script type="module">
import {getCLS} from 'https://unpkg.com/web-vitals?module';
// Logs CLS as the value changes.
getCLS(console.log, true);
</script>
The observed result will look like the below.
Here is the LayoutShift
object
{
"name": "",
"entryType": "layout-shift",
"startTime": 2396.800000000745,
"duration": 0,
"value": 0.0005956060112184058,
"hadRecentInput": false,
"lastInputTime": 0,
"sources": [
{
"previousRect": {
"x": 478,
"y": 14,
"width": 587,
"height": 45,
"top": 14,
"right": 1065,
"bottom": 59,
"left": 478
},
"currentRect": {
"x": 465,
"y": 14,
"width": 600,
"height": 44,
"top": 14,
"right": 1065,
"bottom": 58,
"left": 465
},
"node": null
}
]
}