A Pen by deepesh141291 on CodePen.
-
-
Save gagimilicevic/f41a8a1f429cdffee04745ad925ccd8b to your computer and use it in GitHub Desktop.
Lazy Loading CSS Background Images with Intersection Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*{ | |
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