Table of Contents

Layout Shift: How to prevent it ? (Cumulative Layout Shit / CLS)

About

A layout shift occurs when the rendering of the web page shifts / move element from their current position.

Causes

Image

For instance:

That's what's called a layout shift

1)

Solution:

Style

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");
});

Measurement

Occurences: Devtool

In the devtool, layout shift can be seen

Layout Shift Devtool Performance

Devtool Chorme Rendering Layout Shift

Cumulative layout shift

The Cumulative layout shift or CLS is a web core vital metrics that groups all layout shift during page load.

Devtool Chrome Web Core Vital Overlay

Calculation Example with Perfume

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;
    }
  },
});