Recently, I revamped our new website with a completely new catchy design. It has many sliders, which is a very popular feature of most websites, and I wanted to implement it in a way that would not cause layout shifts. I choose Slick as the library to implement the slider.
All I need to do is include the library with a script
tag, the required CSS from Slick and initialize it with a simple JavaScript.
$(window).on("load", function () {
$(".js-slider").slick({
arrow: true,
dots: true
});
});
HTML code would look like
<div class="container">
<section class="js-slider">
<div class="slide">
<img src="https://via.placeholder.com/350x300?text=1" />
</div>
<div class="slide">
<img src="https://via.placeholder.com/350x300?text=2" />
</div>
<div class="slide">
<img src="https://via.placeholder.com/350x300?text=3" />
</div>
</section>
</div>
Notice that all images will be rendered first before the JS kicks in to initialize the slider that could cause a layout shift, as shown in the screenshot below. Locally, we usually don’t need to worry about the layout shift, but it is a must for our end users.
I could do a pretty easy fix with just a few lines of CSS. We need to ensure our images have the same styles before and after the scripts are parsed and executed. In this case, all it takes is the following:
.js-slider {
& > .slide:not(:first-child) {
display: none;
}
}
This way, we hide everything but the first slide in our carousel and add the padding on the sides that Slick will add after it loads. Slick will add extra wrapping elements to our slides, so the immediate children selector (>
) will make the styles only apply before it loads.
Notice that the $(window).on("load"
is important because if you use $(document).ready()
it will not work as expected. $(window).on("load"
will make sure the images are rendered before the slider is initialized.