-
Notifications
You must be signed in to change notification settings - Fork 220
/
lazyload-css.js
92 lines (70 loc) · 2.24 KB
/
lazyload-css.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
function rocket_css_lazyload_launch() {
const usable_pairs = typeof rocket_pairs === 'undefined' ? [] : rocket_pairs;
const excluded_pairs = typeof rocket_excluded_pairs === 'undefined' ? [] : rocket_excluded_pairs;
excluded_pairs.map(pair => {
const selector = pair.selector;
const nodes = document.querySelectorAll(selector);
nodes.forEach(el => {
el.setAttribute(`data-rocket-lazy-bg-${pair.hash}`, 'excluded');
});
});
const styleElement = document.querySelector('#wpr-lazyload-bg');
const threshold = rocket_lazyload_css_data.threshold || 300;
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const pairs = usable_pairs.filter(s => entry.target.matches(s.selector));
pairs.map(pair => {
if (pair) {
styleElement.innerHTML += pair.style;
pair.elements.forEach(el => {
// Stop observing the target element
observer.unobserve(el);
el.setAttribute(`data-rocket-lazy-bg-${pair.hash}`, 'loaded');
});
}
})
}
});
}, {
rootMargin: threshold + 'px'
});
function lazyload(e = []) {
const pass = e.length > 0;
if(! pass ) {
return;
}
usable_pairs.forEach(pair => {
try {
const elements = document.querySelectorAll(pair.selector);
elements.forEach(el => {
if( el.getAttribute(`data-rocket-lazy-bg-${pair.hash}`) === 'loaded' ||
el.getAttribute(`data-rocket-lazy-bg-${pair.hash}`) === 'excluded')
{
return;
}
observer.observe(el);
// Save el in the pair object (create a new empty array if it doesn't exist)
(pair.elements ||= []).push(el);
});
} catch (error) {
console.error(error);
}
});
}
lazyload();
const observe_DOM = (function(){
const MutationObserver = window.MutationObserver;
return function( obj, callback ){
if( !obj || obj.nodeType !== 1 ) return;
// define a new observer
const mutationObserver = new MutationObserver(callback);
// have the observer observe for changes in children
mutationObserver.observe( obj, { attributes: true, childList:true, subtree:true })
return mutationObserver
}
})()
const body = document.querySelector('body');
observe_DOM(body, lazyload)
}
rocket_css_lazyload_launch();