← Back to Demos

Lazy Loading Images

圖片延遲載入

Image slider with native lazy loading using loading="lazy" and IntersectionObserver.

使用原生 loading="lazy" 和 IntersectionObserver 的圖片延遲載入輪播。

  • Lazy image 1
  • Lazy image 2
  • Lazy image 3
  • Lazy image 4
  • Lazy image 5
  • Lazy image 6

Source Code

js
var DS = DriftSlider;
var slider = new DS.DriftSlider('.drift-slider', {
  modules: [DS.Navigation, DS.Pagination, DS.A11y],
  slidesPerView: 1,
  spaceBetween: 20,
  speed: 400,
  grabCursor: true,
});

// IntersectionObserver for lazy-loaded images
var images = document.querySelectorAll('.drift-slide img[loading="lazy"]');
var observer = new IntersectionObserver(function(entries) {
  entries.forEach(function(entry) {
    if (entry.isIntersecting) {
      var img = entry.target;
      img.addEventListener('load', function() {
        img.classList.add('loaded');
      });
      // If already loaded (cached), add class immediately
      if (img.complete) {
        img.classList.add('loaded');
      }
      observer.unobserve(img);
    }
  });
}, { rootMargin: '100px' });

images.forEach(function(img) {
  observer.observe(img);
});