异步可视加载
web | des |
---|---|
IntersectionObserver |
IntersectionObserver
js
const intersectionObserver = new IntersectionObserver((entries) => {
// 如果 intersectionRatio 为 0,则目标在视野外,
// 我们不需要做任何事情。
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
console.log("Loaded new items");
});
// 开始监听
intersectionObserver.observe(document.querySelector(".scrollerFooter"));
useIntersectionObserver
图片懒加载
js
import { useIntersectionObserver } from '@vueuse/core'
const imgLazy = {
mounted: (el) => {
// 1. 缓存当前图片路径
const catchSrc = el.src
// 2. 设置临时占位图,默认不加载网络图片
el.src = 'https://res.lgdsunday.club/img-load.png'
// 3. 利用 useIntersectionObserver 监听
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) {
// 5. 渲染
el.src = catchSrc
// 6. 停止监听
stop()
}
})
}
}
export default {
install: (app) => {
app.directive('imgLazy', imgLazy)
}
}