|
1 | 1 | import { isArray } from './isArray' |
2 | 2 | import { isStr } from './isStr' |
3 | 3 | export function lazyLoad(imgList: any, root: Element, rootMargin = '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) |
| 4 | + try { |
| 5 | + if (isStr(imgList)) |
| 6 | + imgList = document.querySelectorAll(imgList) |
| 7 | + if (imgList.length !== undefined) |
| 8 | + imgList = [...imgList] |
| 9 | + const observer = new IntersectionObserver( |
| 10 | + (entries, observer) => { |
| 11 | + entries.forEach((entry) => { |
| 12 | + /* 替换属性 */ |
| 13 | + console.log(entry.isIntersecting) |
| 14 | + if (entry.isIntersecting) { |
| 15 | + (entry.target as HTMLImageElement).src = (entry.target as any).dataset.src |
| 16 | + observer.unobserve(entry.target) |
| 17 | + } |
| 18 | + }) |
| 19 | + }, |
| 20 | + { rootMargin, root, threshold }) |
| 21 | + if (isArray(imgList)) |
| 22 | + (imgList as Element[]).forEach(img => observer.observe(img)) |
| 23 | + else observer.observe(imgList as Element) |
| 24 | + } |
| 25 | + catch (error: any) { |
| 26 | + throw new Error(error) |
| 27 | + } |
23 | 28 | } |
24 | 29 |
|
0 commit comments