LightSlider is one of my favorite responsive jQuery carousel plugins to use. It’s fast, it’s lightweight, and it’s relatively easy to install and use on most websites. However, it’s still dependent upon JavaScript and jQuery, and therefore has to wait for the page to load before it loads, which can leave an undesirable flash of unstyled content. This article is all about how to hide unstyled slides until jQuery LightSlider is fully loaded.
Context
LightSlider uses really simple HTML markup to render a carousel. The code is a basic unordered list ul
element filled with normal list items li
– no fancy structure or extraneous classes needed.
<ul id="lightslider"> <li>Slide 1</li> <li>Slide 2</li> <li>Slide 3</li> ... </ul>
The Problem
By default, HTML unordered lists create block-level elements that stack vertically one on top of the next. Stacked elements is how LightSlider slides appear prior to the page and slider fully loading. For a brief moment, it displays as a flash of unstyled content.
A flash of unstyled content makes your website look like the page is jumping in to place, as opposed to loading correctly from the start. It’s wonky behavior that results in cumulative layout shifts.
According to Google’s core web vitals, layout shifts can negatively impact search engine optimization. It is in your best interest to minimize or remove any kind of layout shift from your website, but especially if you are trying to rank a page in search engine results.
A Solution
One reason LightSlider is a personal favorite carousel plugin of mine is because it comes with a built-in solution for fixing the flash or unstyled content layout shift issue.
Baked into LightSlider’s CSS stylesheet is a class named .cS-hidden
.
.cS-hidden { height: 1px; opacity: 0; filter: alpha(opacity=0); overflow: hidden; }
Adding the cS-hidden class to your unordered list element visually hides the carousel and its content.
<ul id="lightslider" class="cS-hidden"> <li>Slide 1</li> <li>Slide 2</li> <li>Slide 3</li> ... </ul>
Combined with LightSliders onSliderLoad()
callback function, you can hide the unstyled carousel using the .cS-hidden class and then show the carousel once the JavaScript has fully loaded.
$('#lightslider').lightSlider({ // When the slider loads, remove the cS-hidden class onSliderLoad: function(el) { el.removeClass('cS-hidden'); } });
Now, you will no longer experience layout shifts or see flashes of unstyled content when using jQuery LightSlider.
0 Comments