Owl Carousel CLS (Cumulative Layout Shift) fix
Overview
Sliders and carousels are an extremely common web component used on many websites these days, for better or worse (to read more about the worse part, a good article here). However, as with many things web development related, if the client insists on having a slider/carousel on the home page, as a web developer we have to accommodate that.
Background
Google has announced that from June 2021, they will start to consider “Page Experience” as part of Search ranking, as measured by a set of metrics called Core Web Vitals.
The Core Web Vitals are a set of three metrics designed to measure the “core” experience of whether a website feels fast or slow to the users, and so gives a good experience.
In this article, we will concentrate on CLS (Cumulative Layout Shift) and how sliders/carousels such as Owl Carousel negatively impact CLS scores and provide an easy fix using CSS only.
As per Google documentation:
CLS measures the sum total of all individual layout shift scores for every unexpected layout shift that occurs during the entire lifespan of the page. The score is zero to any positive number, where zero means no shifting and the larger the number, the more layout shift on the page. This is important because having pages elements shift while a user is trying to interact with it is a bad user experience. If you can’t seem to find the reason for a high value, try interacting with the page to see how that affects the score.
Owl Carousel CLS Problem
Using a standard implementation of Owl Carousel, you will typically end up with a CLS score of 0.5 or more. According to Google, anything greater than 0.25 is considered poor, between 0.1 and 0.25 needs improvement, and less than 0.1 is good.
Solution
Owl Carousel chooses to hide the entire carousel on initial page load until all javascript has been loaded – hence why you end with a large layout shift.
The solution is to add a small amount of CSS that displays the first carousel image on initial page load so that the DOM can properly reserve the space required for the carousel, and therefore minimise any layout shift.
.owl-carousel {
display: block;
}
.owl-carousel .slide-owl-wrap:not(:first-child) {
display: none;
}
.owl-carousel img {
width: 100%;
}
To make this CSS work, a small change to the standard html structure as laid out in the Owl Carousel class documentation is required. Basically an extra div within each div.owl-item needs to be added as shown below:
<div class="owl-carousel owl-theme owl-loaded">
<div class="owl-stage-outer">
<div class="owl-stage">
<div class="owl-item">
<div class="slide-owl-wrap">
<img src="..." />
</div>
</div>
<div class="owl-item">
<div class="slide-owl-wrap">
<img src="..." />
</div>
</div>
<div class="owl-item">
<div class="slide-owl-wrap">
<img src="..." />
</div>
</div>
</div>
</div>
</div>
With this small change, our CLS score has improved dramatically.