Skip to content

Instantly share code, notes, and snippets.

@smallpaes
Created June 16, 2020 15:25
Show Gist options
  • Save smallpaes/d165b4f2213329919031b321888089e3 to your computer and use it in GitHub Desktop.
Save smallpaes/d165b4f2213329919031b321888089e3 to your computer and use it in GitHub Desktop.
const imageContainer = document.querySelector('.image-container')
const imageList = document.querySelector('.image-list')
// 選到目標元素
const loadingObserver = document.querySelector('.observer')
// 每次載入的圖片數量
const IMAGE_PER_PAGE = 3
// 每次要取得圖片的頁碼
let page = 1
// 設定在什麼情況下觸發 callback 函式
const options = {
root: imageContainer,
rootMargin: "0px 0px 200px 0px",
threshold: 0
}
// 載入圖片的函式
const fetchImages = () => {
axios.get(`https://picsum.photos/v2/list?page=${page}&limit=${IMAGE_PER_PAGE}`)
.then(res => {
res.data.forEach(image => {
imageList.innerHTML += `
<li class="image-item"><img class="image" src=${image.download_url}></li>
`
})
// 更新頁碼
page += 1
})
}
// callback 函式
const callback = ([entry]) => {
if (entry && entry.isIntersecting) {
fetchImages()
}
}
// 創建一個 observer
let observer = new IntersectionObserver(callback, options)
// 觀察目標元素
observer.observe(loadingObserver)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment