A layout shift occurs when the rendering of the web page shifts / move element from their current position.
For instance:
That's what's called a layout shift
Solution:
When you change a layout css property after page load (the first rendering), you will also create a layout shift.
Solution: If you want to change two layout property at the same time, you should use the window.requestAnimationFrame function to avoid a layout shift.
Example with a dynamic correction of a fixed top header such as the Bootstrap navbar where:
window.requestAnimationFrame(function() {
let fixedNavbar = document.querySelector(".navbar[data-type=\"fixed-top\"]")
fixedNavbar.classList.add("fixed-top");
let offsetHeight = fixedNavbar.offsetHeight;
document.body.style.setProperty("padding-top",offsetHeight+"px");
});
In the devtool, layout shift can be seen
The Cumulative layout shift or CLS is a web core vital metrics that groups all layout shift during page load.
Example with perfume
<button>Click to see the cumulative value</button>
setTimeout(function(){
let button = document.querySelector("button");
button.style.display = "block";
button.style.marginLeft= "auto";
button.style.marginRight= "auto";
button.style.width= "fit-content";
}
,2000);
new Perfume({
analyticsTracker: options => {
const { metricName, data, eventProperties, navigatorInformation, vitalsScore, } = options;
switch (metricName) {
case 'cls':
console.log('cumulativeLayoutShift value: '+data);
break;
case 'clsFinal':
console.log('cumulativeLayoutShiftFinal: '+data);
break;
}
},
});