2020-04-12 00:23:16 +02:00
|
|
|
/* eslint-disable indent */
|
|
|
|
export class LazyLoader {
|
|
|
|
constructor(options) {
|
|
|
|
this.options = options;
|
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
createObserver() {
|
|
|
|
const callback = this.options.callback;
|
2020-04-11 22:51:11 +02:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
const observer = new IntersectionObserver(
|
2020-04-12 03:54:09 +02:00
|
|
|
(entries) => {
|
2020-04-12 00:23:16 +02:00
|
|
|
entries.forEach(entry => {
|
|
|
|
callback(entry);
|
2020-06-22 09:14:13 +02:00
|
|
|
});
|
|
|
|
},
|
|
|
|
{rootMargin: '25%'});
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
this.observer = observer;
|
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
addElements(elements) {
|
|
|
|
let observer = this.observer;
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
if (!observer) {
|
|
|
|
this.createObserver();
|
|
|
|
observer = this.observer;
|
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
Array.from(elements).forEach(element => {
|
|
|
|
observer.observe(element);
|
|
|
|
});
|
2019-01-10 15:39:37 +03:00
|
|
|
}
|
|
|
|
|
2020-04-15 14:39:44 +02:00
|
|
|
destroyObserver() {
|
2020-04-12 00:23:16 +02:00
|
|
|
const observer = this.observer;
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
if (observer) {
|
|
|
|
observer.disconnect();
|
|
|
|
this.observer = null;
|
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
}
|
|
|
|
|
2020-04-15 14:39:44 +02:00
|
|
|
destroy() {
|
2020-04-12 00:23:16 +02:00
|
|
|
this.destroyObserver();
|
|
|
|
this.options = null;
|
2019-01-10 15:39:37 +03:00
|
|
|
}
|
2020-04-12 00:23:16 +02:00
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
|
|
|
function unveilElements(elements, root, callback) {
|
|
|
|
if (!elements.length) {
|
|
|
|
return;
|
|
|
|
}
|
2020-04-12 00:23:16 +02:00
|
|
|
const lazyLoader = new LazyLoader({
|
2019-01-10 15:39:37 +03:00
|
|
|
callback: callback
|
|
|
|
});
|
|
|
|
lazyLoader.addElements(elements);
|
|
|
|
}
|
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
export function lazyChildren(elem, callback) {
|
2019-01-10 15:39:37 +03:00
|
|
|
unveilElements(elem.getElementsByClassName('lazy'), elem, callback);
|
2020-04-12 00:23:16 +02:00
|
|
|
}
|
2019-01-10 15:39:37 +03:00
|
|
|
|
2020-04-12 00:23:16 +02:00
|
|
|
/* eslint-enable indent */
|
|
|
|
export default {
|
|
|
|
LazyLoader: LazyLoader,
|
|
|
|
lazyChildren: lazyChildren
|
|
|
|
};
|