Skip to content

Instantly share code, notes, and snippets.

Last active November 18, 2022 04:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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) {
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;
}, 200);
document.addEventListener('scroll', lazyLoad);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment