Optimize visible with observables

This commit is contained in:
Andros Fenollosa 2020-08-03 17:02:50 +02:00
parent e02334b46e
commit b9bb0d694b

View File

@ -12,10 +12,12 @@ function addEventVisible() {
let eventNotVisible = 'is-not-visible'; let eventNotVisible = 'is-not-visible';
let elementsVisibles = getElementsValidatesByEvent(eventVisible); let elementsVisibles = getElementsValidatesByEvent(eventVisible);
let elementsNotVisibles = getElementsValidatesByEvent(eventNotVisible); let elementsNotVisibles = getElementsValidatesByEvent(eventNotVisible);
window.addEventListener("scroll", () => {
// Visible // Visible
elementsVisibles.forEach((element) => { const onIntersectionVisible = (entries) => {
if (isInViewport(element)) { entries.forEach((entry) => {
let element = entry.target;
if (entry.isIntersecting) {
let params = splitParams(element, eventVisible); let params = splitParams(element, eventVisible);
switch(params.functionParent) { switch(params.functionParent) {
case 'class': case 'class':
@ -31,9 +33,17 @@ function addEventVisible() {
} }
} }
}); });
// Not visible };
elementsNotVisibles.forEach((element) => { const observerVisible = new IntersectionObserver(onIntersectionVisible);
if (!isInViewport(element)) { elementsVisibles.forEach((element) => {
observerVisible.observe(element);
});
// Not visible
const onIntersectionNotVisible = (entries) => {
entries.forEach((entry) => {
let element = entry.target;
if (!entry.isIntersecting) {
let params = splitParams(element, eventNotVisible); let params = splitParams(element, eventNotVisible);
switch(params.functionParent) { switch(params.functionParent) {
case 'class': case 'class':
@ -49,6 +59,11 @@ function addEventVisible() {
} }
} }
}); });
}, false); };
const observerNotVisible = new IntersectionObserver(onIntersectionNotVisible);
elementsNotVisibles.forEach((element) => {
observerNotVisible.observe(element);
});
} }