/
lozad.js
71 lines (63 loc) 路 1.67 KB
/
lozad.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
const defaultConfig = {
rootMargin: '0px',
threshold: 0,
load(element) {
if (element.getAttribute('data-src')) {
element.src = element.getAttribute('data-src')
}
if (element.getAttribute('data-srcset')) {
element.srcset = element.getAttribute('data-srcset')
}
if (element.getAttribute('data-background-image')) {
element.style.backgroundImage = 'url(' + element.getAttribute('data-background-image') + ')'
}
}
}
function markAsLoaded(element) {
element.setAttribute('data-loaded', true)
}
const isLoaded = element => element.getAttribute('data-loaded') === 'true'
const onIntersection = load => (entries, observer) => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
observer.unobserve(entry.target)
if (!isLoaded(entry.target)) {
load(entry.target)
markAsLoaded(entry.target)
}
}
})
}
export default function (selector = '.lozad', options = {}) {
const {rootMargin, threshold, load} = {...defaultConfig, ...options}
let observer
if (window.IntersectionObserver) {
observer = new IntersectionObserver(onIntersection(load), {
rootMargin,
threshold
})
}
return {
observe() {
const elements = document.querySelectorAll(selector)
for (let i = 0; i < elements.length; i++) {
if (isLoaded(elements[i])) {
continue
}
if (observer) {
observer.observe(elements[i])
continue
}
load(elements[i])
markAsLoaded(elements[i])
}
},
triggerLoad(element) {
if (isLoaded(element)) {
return
}
load(element)
markAsLoaded(element)
}
}
}