-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazyloading.js
75 lines (67 loc) · 2.33 KB
/
lazyloading.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
function Lazyloading({ LAZY_LOADING_ATTRIBUTE, LAZY_LOADING_VIEWPORT_OFFSET, LAZY_LOADING_SCROLL_DEBOUNCE }) {
const delay = (() => {
let timer = 0;
return (callback, ms) => {
clearTimeout(timer);
setTimeout(callback, ms);
};
})();
const isInViewport = (node) => {
if ((LAZY_LOADING_VIEWPORT_OFFSET + node.offsetTop) > window.pageYOffset
&& (node.offsetTop) < (window.outerHeight + window.pageYOffset)
) {
if ((LAZY_LOADING_VIEWPORT_OFFSET + node.offsetLeft) > window.pageXOffset
&& (node.offsetLeft) < (window.pageXOffset + window.outerWidth)) {
return true;
}
}
return false;
};
const processLazyloadImageNode = (node) => {
if (isInViewport(node)) {
if (node.attributes[LAZY_LOADING_ATTRIBUTE]) {
node.src = node.attributes[LAZY_LOADING_ATTRIBUTE].value;
node.attributes.removeNamedItem(LAZY_LOADING_ATTRIBUTE)
}
}
}
const config = {
subtree: true,
attributes: true,
childList: true
};
const nodesHandler = (nodes, handler) => {
return nodes.forEach((node) => {
if (!node
&& ((node.localName.toLowerCase() !== 'img')
|| !node.localName
|| !node.attributes
|| !node.attributes[LAZY_LOADING_ATTRIBUTE])
) {
if (node.childNodes && node.childNodes.length) {
nodesHandler(node.childNodes, handler);
}
return;
}
return handler(node);
});
};
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutationRecord) => {
let nodes = mutationRecord.addedNodes;
if (!nodes || !nodes.length) {
return;
}
nodesHandler(nodes, processLazyloadImageNode);
});
});
observer.observe(document, config);
window.addEventListener('scroll', function (e) {
delay(() => {
e.target.querySelectorAll(`img[${LAZY_LOADING_ATTRIBUTE}]`).forEach(processLazyloadImageNode);
}, LAZY_LOADING_SCROLL_DEBOUNCE);
});
return {
processLazyloadImageNode
};
}