图片懒加载
ts
interface LazyImageOptions {
errorImgSrc?: string;
root?: Element | Document | null;
rootMargin?: string;
threshold?: number | number[];
}
function lazyImage(options: LazyImageOptions = {}) {
const imgs = document.querySelectorAll<HTMLImageElement>('img[data-src]');
const len = imgs.length;
let index = 0;
const {
errorImgSrc = '/error.png',
root = null,
threshold = 0,
rootMargin = '0px',
} = options;
if (len === 0) return;
function loadImg(img: HTMLImageElement) {
const src = img.getAttribute('data-src') || '';
img.setAttribute('src', src);
img.onload = () => {
img.removeAttribute('data-src');
};
img.onerror = () => {
img.src = errorImgSrc;
};
}
const observer = new IntersectionObserver(
(entries, ob) => {
for (const entry of entries) {
if (entry.isIntersecting) {
const el = entry.target;
if (el instanceof HTMLImageElement) {
loadImg(el);
ob.unobserve(el);
index++;
if (index === len) {
ob.disconnect();
}
}
}
}
},
{ root, rootMargin, threshold }
);
for (const img of imgs) {
observer.observe(img);
}
}