Skip to content

Instantly share code, notes, and snippets.

@mciastek
Last active September 21, 2019 18:10
Show Gist options
  • Save mciastek/386dd3e4de3184c088270c7c187c48f9 to your computer and use it in GitHub Desktop.
Save mciastek/386dd3e4de3184c088270c7c187c48f9 to your computer and use it in GitHub Desktop.
import throttle from 'lodash/throttle';
const images = [...document.querySelectorAll('img')];
let windowHeight = window.innerHeight;
// We need to store images' sizes in a WeakMap
// to get them later in scroll handler
const imagesSizes = new WeakMap();
// This method allows to get top and height of each image
// and store them in WeakMap
const getImagesSizes = () => {
images.forEach((image) => {
const { top, height } = image.getBoundingClientRect();
imagesSizes.set(image, { top, height });
});
};
const onScroll = () => {
images.forEach(async (image) => {
// If image has been already loaded, bail out
if (image.classList.contains('loaded')) {
return;
}
const { top, height } = imagesSizes.get(image);
// We use isInViewport method from previous example
if (isInViewport({ top, height, windowHeight }) {
try {
// We use loadImage method from previous example
await loadImage(image.src);
image.classList.add('loaded');
} catch (error) {
console.error(error);
}
}
});
};
// When window dimensions changed, update sizes
const onResize = () => {
windowHeight = window.innerHeight;
getImagesSizes();
};
getImagesSizes();
window.addEventListener('scroll', throttle(onScroll));
window.addEventListener('resize', onResize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment