2021-12-11

Tech Programing

程式人小天地

Lazy loading of multiple sliders using verlock/vanilla-lazyload

1 min read


There are several sliders with different settings in the project, following the library documentation, but the problem is that the documentation describes an example for several sliders with the same settings. My approach:

const gallerySlider = {
  slidesPerView: 1,
  slidesPerColumnFill: 'row',
  spaceBetween: 50,
  observer: true,
  observeParents: true,
  observeSlideChildren: true,
  grid: {
    fill: 'row',
  },
  pagination: {
    el: '.swiper-pagination',
    type: 'fraction',
    clickable: 'true',
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  breakpoints: {
    421: {
      grid: {
        rows: 2,
      },
      slidesPerView: 2,
      spaceBetween: 34,
      slidesPerGroup: 2,
    },
    1200: {
      grid: {
        rows: 2,
      },
      slidesPerGroup: 2,
      spaceBetween: 34,
    },
    1600: {
      grid: {
        rows: 2,
      },
      slidesPerView: 3,
      slidesPerGroup: 3,
      spaceBetween: 50,
    },
  },
  a11y: {
    prevSlideMessage: 'Prev',
    nextSlideMessage: 'Next',
  },
  on: {
    // LazyLoad swiper images after swiper initialization
    afterInit: (swiper) => {
      new LazyLoad({
        container: swiper.el,
        cancel_on_exit: false
      });
    }
  }
};

then I initialize the vanilla-lazyload:

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, gallerySlider); 
// gallerySlider - settings Swiper-slider
  }
});

I also tried initializing a new instance of the library for each slider, but this approach also turned out to be ineffective, the settings for the first slider were applied to all sliders

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, gallerySlider);
  }
});

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, projectsSlider);
  }
});

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, eventsSlider);
  }
});



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *