Created
July 25, 2018 16:50
-
-
Save murtaugh/3a8d096728e73479fd40ded0e6dfe6f1 to your computer and use it in GitHub Desktop.
Wilto's Lazy Loader for images
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
(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