Last active
June 8, 2020 16:31
-
-
Save g3luka/d3dacdd9abaa0fb417b16c84109bd910 to your computer and use it in GitHub Desktop.
Images Lazy Loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const imageLazyLoad = (element) => { | |
const src = element.getAttribute('data-src'); | |
element.setAttribute('src', src); | |
element.removeAttribute('data-src'); | |
} | |
const observador = new IntersectionObserver(function(entries) { | |
entries.forEach(function(entry) { | |
// if (entry.isIntersecting === true || entryintersectionRatio > 0) { | |
if (entry.isIntersecting !== true) return; | |
imageLazyLoad(entry.target); | |
observador.unobserve(entry.target); | |
}); | |
}, { | |
rootMargin: '100px' | |
}); | |
const images = document.querySelectorAll('#post-content img[data-src]'); | |
images.forEach(image => { | |
console.log(image); | |
observador.observe(image); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const imageLazyLoad = (element) => { | |
const src = element.getAttribute('data-src'); | |
element.setAttribute('src', src); | |
element.removeAttribute('data-src'); | |
} | |
document.addEventListener('scroll', (event) => { | |
const all = document.querySelectorAll('.lazyload[data-src]'); | |
if ( ! all) return; | |
all.map((element) => { | |
const callback = element.getAttribute('data-callback') || imageLazyLoad; | |
const elementGap = element.hasAttribute('data-gap') ? element.getAttribute('data-gap') : 100; | |
const elementTop = element.offsetTop - elementGap; | |
const elementBottom = elementTop + element.offsetHeight + elementGap; | |
const screenTop = document.documentElement.scrollTop; | |
const screenBottom = screenTop + window.innerHeight; | |
const isReady = elementBottom > screenTop && elementTop < screenBottom; | |
if (isReady) callback(element); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment