JS懒加载
基于h5 IntersectionObserver API 实现的高性能图片懒加载 vue3 Hook MDN
/**
* 图片懒加载
* @returns imgLazyLoad
*/
export const useLazy = (): {
imgLazyLoad: (el?: string) => void;
} => {
// el 需要懒加载的图片类名
const imgLazyLoad = (el: string = ".lazyLoad") => {
const io = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
// 图片进入可视区域
if (entry.isIntersecting) {
const imgEl: any = entry.target
// 图片赋值
imgEl.src = imgEl.dataset.url
// 取消 再次监听这张图片
io.unobserve(imgEl)
}
});
});
const lazyElList = document.querySelectorAll(el);
lazyElList.forEach((el) => {
io.observe(el);
});
}
return {
imgLazyLoad
}
}