Skip to content

Instantly share code, notes, and snippets.

@g3luka
Last active June 8, 2020 16:31
Show Gist options
  • Save g3luka/d3dacdd9abaa0fb417b16c84109bd910 to your computer and use it in GitHub Desktop.
Save g3luka/d3dacdd9abaa0fb417b16c84109bd910 to your computer and use it in GitHub Desktop.
Images Lazy Loading
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);
});
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