-
Notifications
You must be signed in to change notification settings - Fork 0
/
LazyLoadImages.js
95 lines (80 loc) · 2.63 KB
/
LazyLoadImages.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
export class LazyLoadImages {
// with our All.js instantiation, this does not get called until DOM ready, so no check
constructor () {
if ('IntersectionObserver' in window) {
this.modernBrowsers()
document.body.addEventListener('Ajax:Rendered', () => {
this.modernBrowsers()
})
} else {
this.oldskool()
document.body.addEventListener('Ajax:Rendered', () => {
this.oldskool()
})
}
}
modernBrowsers () {
let lazyImages = [].slice.call(
document.querySelectorAll('[data-lazy-load]')
)
let lazyImageObserver = new window.IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target
if (lazyImage.dataset.src) {
lazyImage.src = lazyImage.dataset.src
}
if (lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset
}
lazyImage.removeAttribute('data-lazy-load')
lazyImageObserver.unobserve(lazyImage)
}
})
})
lazyImages.forEach(image => {
lazyImageObserver.observe(image)
})
}
oldskool () {
let active = false
let lazyImages = [].slice.call(
document.querySelectorAll('[data-lazy-load]')
)
const lazyLoad = function () {
if (active === false) {
active = true
setTimeout(function () {
lazyImages.forEach(function (lazyImage) {
if (
lazyImage.getBoundingClientRect().top <= window.innerHeight &&
lazyImage.getBoundingClientRect().bottom >= 0 &&
window.getComputedStyle(lazyImage).display !== 'none'
) {
if (lazyImage.dataset.src) {
lazyImage.src = lazyImage.dataset.src
}
if (lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset
}
lazyImage.removeAttribute('data-lazy-load')
lazyImages = lazyImages.filter(function (image) {
return image !== lazyImage
})
if (lazyImages.length === 0) {
document.removeEventListener('scroll', lazyLoad)
window.removeEventListener('resize', lazyLoad)
window.removeEventListener('orientationchange', lazyLoad)
}
}
})
active = false
}, 200)
}
}
document.addEventListener('scroll', lazyLoad)
window.addEventListener('resize', lazyLoad)
window.addEventListener('orientationchange', lazyLoad)
lazyLoad()
}
}