Skip to content

Instantly share code, notes, and snippets.

@deepesh141291
Created July 15, 2018 04:51
Show Gist options
  • Save deepesh141291/4b180fcd880d9729df13efc948e43ba2 to your computer and use it in GitHub Desktop.
Save deepesh141291/4b180fcd880d9729df13efc948e43ba2 to your computer and use it in GitHub Desktop.
Lazy Loading CSS Background Images with Intersection Observer
<div class="wrapper">
<div class="lazy-background img"></div>
<div class="lazy-background img"></div>
<div class="lazy-background img"></div>
<div class="lazy-background img"></div>
<div class="lazy-background img"></div>
</div>
document.addEventListener("DOMContentLoaded", function() {
var lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-background"));
if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) {
let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
lazyBackgroundObserver.unobserve(entry.target);
}
});
});
lazyBackgrounds.forEach(function(lazyBackground) {
lazyBackgroundObserver.observe(lazyBackground);
});
}
});
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
.wrapper{
max-width: 960px;
margin: 0 auto;
}
.lazy-background{
margin: 1024px auto 128px;
display: block;
background-repeat: no-repeat;
background-size: contain;
}
.img{
padding-top: 28.0519480519%;
background-image: url("https://picsum.photos/200/300/?blur");
}
.img.visible{
background-image: url("https://picsum.photos/200/300/?random");
}
.two{
padding-top: 55%;
background-image: url("https://picsum.photos/200/300/?blur");
}
.two.visible{
background-image: url("https://picsum.photos/200/300/?random");
}
.three{
padding-top: 66.625%;
background-image: url("https://picsum.photos/200/300/?blur");
}
.three.visible{
background-image: url("https://picsum.photos/200/300/?random");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment