Skip to content

Instantly share code, notes, and snippets.

@yakuzaaaa
Last active November 18, 2022 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yakuzaaaa/bb1d1cca11238bd3d6a8a78500e3a6ce to your computer and use it in GitHub Desktop.
Save yakuzaaaa/bb1d1cca11238bd3d6a8a78500e3a6ce to your computer and use it in GitHub Desktop.
/*
A very inefficient but with best browser support way would be to check if the
clientBoundingRect of the image is currently inside the viewport or not on every
scroll event, damn! it's costly!
*/
/*
Let's say the images in HTML are:
<img data-src="someimage1.png" class="lazy-image">
<img data-src="someimage2.png" class="lazy-image">
<img data-src="someimage3.png" class="lazy-image">
<img data-src="someimage4.png" class="lazy-image">
<img data-src="someimage5.png" class="lazy-image">
*/
/*
Then the following javaSscript code
*/
(function() {
document.addEventListener('DOMContentLoaded', () => {
let debouncedLazyLoad = null;
function lazyLoad() {
if(debouncedLazyLoad) {
clearTimeout(debouncedLazyLoad);
}
debouncedLazyLoad = setTimeout(() => {
const images = document.querySelectorAll('.lazy-image');
/**
Foreach image we need to check if it's TOP is less than page's height (This means
the current immediate bottom)
*/
const pageCurrentBottom = window.innerHeight;
images.forEach((img) => {
const imgTop = img.getBoundingClientRect().top;
if(imgTop < pageCurrentBottom) {
img.src = img.dataset.src;
img.classList.remove("lazy-image");
}
}, 200);
});
}
document.addEventListener('scroll', lazyLoad);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment