Wanna see something cool? Check out Angular Spotify 🎧

Slick - prevent layout shift for your slider

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.

Slick - prevent layout shift for your slider

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.

Slick - prevent layout shift for your slider

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.

Source code

Reference

Published 18 Sep 2021

Read more

CSS div jumped when adding a border
Align React Material UI Dialog to the top instead of center
TypeScript - Property 'onerror' does not exist on type 'EventTarget'
TypeScript data structure: Stack
TypeScript data structure: Queue

Follow @tuantrungvo on Twitter for more!