Skip to content

Instantly share code, notes, and snippets.

@smallpaes
Last active June 14, 2020 15:02
Show Gist options
  • Save smallpaes/7b5be31b0b3f4f0e5ec9cac7ce585116 to your computer and use it in GitHub Desktop.
Save smallpaes/7b5be31b0b3f4f0e5ec9cac7ce585116 to your computer and use it in GitHub Desktop.
// 選到頁面中帶有 data-src 屬性的所有元素
const images = document.querySelectorAll('[data-src]')
// 設定在什麼情況下觸發 callback 函式
const options = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
}
// 載入圖片的函式
const loadImage = (img) => {
// 取得元素上 data-src 屬性中的圖片位址
const src = img.getAttribute('data-src')
if (!src) return
// 設定圖片的 src 並放入圖片位址讓瀏覽器載入
img.src = src
// update monitor
}
// callback 函式
const callback = (entries, observer) => {
entries.forEach(entry => {
// 當此圖片進入 viewport 時才載入圖片
if (!entry.isIntersecting) return
// 載入圖片
loadImage(entry.target)
// 停止觀察此圖片
observer.unobserve(entry.target)
})
}
// 創建一個 observer
let observer = new IntersectionObserver(callback, options)
// 觀察所有圖片
images.forEach(image => observer.observe(image))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment