-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazyLoadImagesDemo.js
39 lines (34 loc) · 1.07 KB
/
lazyLoadImagesDemo.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
/*
Lazy Loading Images Demo Using InterSection Observer API
*/
// img container
{/* <img class="js-lazy-images" data-src="example.png" /> */}
const images = document.querySelectorAll('.js-lazy-image');
const config = {
// if the image gets within 50px in the Y axis, start the download
rootMargin: '50px 0px',
threshold: 0.01
}
let observer = new IntersectionObserver(onIntersection, config);
images.forEach(image => {
observer.observe(image);
});
function onIntersection(entries) {
entries.forEach(entry => {
// image inside viewport
if(entry.IntersectionRatio > 0) {
// stop watching and load the image
observer.unobserve(entry.target);
preloadImage(entry.target);
}
});
}
// if browser dont support IntersectionObserver, load images immediately
if(!('IntersectionObserver' in window)){
Array.from(images).forEach(image => preloadImage(image));
} else {
observer = new IntersectionObserver(onIntersection, config);
images.forEach(image => {
observer.observe(image);
});
}