Skip to content

Instantly share code, notes, and snippets.

@RickardAhlstedt
Created September 24, 2019 15:04
Show Gist options
  • Save RickardAhlstedt/d5fbaf198362a4df06a642c85763b036 to your computer and use it in GitHub Desktop.
Save RickardAhlstedt/d5fbaf198362a4df06a642c85763b036 to your computer and use it in GitHub Desktop.
lazyload images
<img class="lazy" src="/images/placeholder.png" data-src="' . $sImageUrl . '" alt="" />
<script type="text/javascript">
document.addEventListener( "DOMContentLoaded", function() {
var lazyImages = [].slice.call( document.querySelectorAll("img.lazy") );
if( "IntersectionObserver" in window ) {
let lazyImageObserver = new IntersectionObserver( function(entries, observer) {
entries.forEach( function(entry) {
if( entry.isIntersecting ) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
} );
} );
lazyImages.forEach( function(lazyImage) {
lazyImageObserver.observe(lazyImage);
} );
} else {
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment