SwiperJS lazy loading - Image not displaying when using data-src as the guide says

7.2k views Asked by At

I have been struggeling trying to implement SwiperJS to my Statamic 3 project.

I have a working carousel/slider that when not using data-src and lazy loading works perfectly fine. But as soon as I try to implement lazy loading following the guide on their website. I get either a white image/background with an infinite loader or a white image/background and no loader.

here is my code:

HTML (the images come from a antlers foreach):

<div class="flex flex-col w-1/3 p-2">
    <div class="h-full w-full swiper-container">
        <div class="h-48 swiper-wrapper">
            {{ foreach:photos }}
                <div class="swiper-slide">
                    <img data-src="{{ value:url }}" class="w-full h-full object-cover object-center swiper-lazy">
                    <div class="swiper-lazy-preloader"></div>
                  </div>
            {{ /foreach:photos}}
        </div>
        <div class="swiper-pagination"></div>
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
    </div>
</div>

My JS:

// core version + navigation, pagination modules:
import Swiper, { Navigation, Pagination } from 'swiper';
import 'swiper/swiper-bundle.css';

// configure Swiper to use modules
Swiper.use([Navigation, Pagination]);


var mySwiper = new Swiper('.swiper-container', {
    slidesPerView: 1,
    spaceBetween: 0,
    slidesPerGroup: 1,
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
    pagination: {
        el: '.swiper-pagination'
    },
    mousewheel: false,
    keyboard: true,
    loop: true,
    parallax: true,
    grabCursor: true,

    // Disable preloading of all images
    preloadImages: false,
    // Enable lazy loading
    lazy: {
        loadPrevNext: true,
    },
});

Current result: Result

Anyone know why my images are not being rendered?

Kind regards, Robbert

1

There are 1 answers

0
gogibogi4 On

You need to import Lazy module.

Change

import Swiper, { Navigation, Pagination } from 'swiper';

to

import Swiper, { Navigation, Pagination, Lazy } from 'swiper';

and change

Swiper.use([Navigation, Pagination]);

to

Swiper.use([Navigation, Pagination, Lazy]);