Skip to content

Commit 8e686ae

Browse files
author
Simon he
committed
chore: add lazyLoad
1 parent 7e139eb commit 8e686ae

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/lazyLoad.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { isArray } from "./isArray";
2+
import { isStr } from "./isStr";
3+
export function lazyLoad(imgList: any, root: Element, rootMargin: string = '0px 0px 200px 0px', threshold: any): void {
4+
if (isStr(imgList))
5+
imgList = document.querySelectorAll(imgList);
6+
if (imgList.length !== undefined)
7+
imgList = [...imgList]
8+
const observer = new IntersectionObserver(
9+
(entries, observer) => {
10+
entries.forEach(entry => {
11+
/* 替换属性 */
12+
console.log(entry.isIntersecting)
13+
if (entry.isIntersecting) {
14+
(entry.target as HTMLImageElement).src = (entry.target as any).dataset.src;
15+
observer.unobserve(entry.target);
16+
}
17+
});
18+
},
19+
{ rootMargin, root, threshold });
20+
if (isArray(imgList))
21+
(imgList as Element[]).forEach(img => observer.observe(img));
22+
else observer.observe(imgList as Element);
23+
}
24+
25+
26+

0 commit comments

Comments
 (0)