-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (51 loc) · 1.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React from 'react';
export default function useLazyLoadImage({
imageAttribute = '[data-img-src]',
imageAttributeKey = 'imgSrc',
rootMargin = '200px 0px',
threshold = 0.01,
debug = false,
dependencies = [],
} = {}) {
function log(...args) {
// eslint-disable-next-line no-console
if (debug) console.log(...args);
}
function loadImage(image) {
const imageUrlToLoad = image.dataset[imageAttributeKey];
log('Loading image url', imageUrlToLoad);
// eslint-disable-next-line no-param-reassign
image.src = imageUrlToLoad;
}
// eslint-disable-next-line consistent-return
React.useEffect(() => {
const images = document.querySelectorAll(imageAttribute);
if (!window.IntersectionObserver) {
log(
'IntersectionObserver not available on this browser, loading all images now'
);
Array.from(images).forEach(image => loadImage(image));
} else {
log(
'Adding intersection observer to all elements that match',
imageAttribute
);
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
log('Unobserving image');
observer.unobserve(entry.target);
loadImage(entry.target);
}
});
},
{ rootMargin, threshold }
);
images.forEach(image => observer.observe(image));
return () => {
images.forEach(image => observer.unobserve(image));
};
}
}, dependencies);
}