Skip to content

Instantly share code, notes, and snippets.

@murtaugh
Created July 25, 2018 16:50
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 murtaugh/3a8d096728e73479fd40ded0e6dfe6f1 to your computer and use it in GitHub Desktop.
Save murtaugh/3a8d096728e73479fd40ded0e6dfe6f1 to your computer and use it in GitHub Desktop.
Wilto's Lazy Loader for images
(function() {
function loadAsync() {
var lazyimgs = document.querySelectorAll( '[data-lazy]' ),
attrswap = function( img ) {
img.src = img.getAttribute( 'data-src' );
img.setAttribute( "sizes", img.getAttribute( 'data-sizes' ) );
img.setAttribute( "srcset", img.getAttribute( 'data-srcset' ) );
img.parentElement.setAttribute( "class", "shown" );
},
supports = "IntersectionObserver" in window
&& "IntersectionObserverEntry" in window
&& "intersectionRatio" in window.IntersectionObserverEntry.prototype;
if( supports ) {
var imgObs = new IntersectionObserver( function( els, obs ) {
els.forEach( function( el ) {
if( el.isIntersecting ) {
var img = el.target;
attrswap( img );
imgObs.unobserve( img );
}
});
});
[].slice.call( lazyimgs ).forEach(function(lazyimg) {
lazyimg.parentElement.classList.add( 'fadein' );
imgObs.observe( lazyimg );
});
} else {
for( i = 0; i < lazyimgs.length; i++ ){
attrswap( lazyimgs[ i ] );
}
}
};
document.addEventListener( "DOMContentLoaded", loadAsync );
document.addEventListener( "loadAsyncImages", loadAsync );
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment