# Intersection Observer API 實作

# Html

  1. 將圖片原本的 src 改為 data-src
  • before <img src="test.jpg" />
  • after <img data-src="test.jpg" />
  1. 添加 lazyload lazy-hidden 到圖片原本的 class
  • before <img class="" />
  • after <img class="lazyload lazy-hidden" />
  1. 最後
<img class="lazyload lazy-hidden" data-src="test.jpg" />

# JS

function onElementObserved (entries, observer) {
    entries.forEach((entry) => {
        if (!entry.isIntersecting) {
            return;
        }
        const img = entry.target;
        if (img.dataset.src) {
            img.setAttribute('src', img.dataset.src);
            img.removeAttribute('data-src');
            img.addEventListener('load', () => {
                img.classList.remove('lazy-hidden');
                img.classList.add('lazy-show');
            })
        }
        observer.unobserve(img);
    }
);
var observer = new IntersectionObserver(onElementObserved);
var lazyImages = document.querySelectorAll('img.lazyload');
lazyImages.forEach((image) => {
    this.observer.observe(image)
});

# CSS

img.lazyload {
  transition: opacity 550ms ease-in;
}
img.lazyload.lazy-hidden {
  opacity: 0;
}
img.lazyload.lazy-show {
  opacity: 1;
}

# 參考來源

  • https://mingjun.lu/blog/lazy-loading-images-with-intersection-observer