Created
May 23, 2019 15:16
-
-
Save TerribleDev/4c0e45faf4dca080f5a6eac702995e0d to your computer and use it in GitHub Desktop.
Lazy load images :)
This file contains hidden or 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
| if(window.IntersectionObserver) { | |
| document.addEventListener("DOMContentLoaded", function() { | |
| var lazyImages = [].slice.call(document.querySelectorAll(".lazy")); | |
| var lazyImageObserver = new IntersectionObserver(function(entries, observer) { | |
| entries.forEach(function(entry) { | |
| if (entry.isIntersecting) { | |
| var lazyImage = entry.target; | |
| if(lazyImage.dataset.src) { | |
| lazyImage.src = lazyImage.dataset.src; | |
| } | |
| if(lazyImage.dataset.srcset) { | |
| lazyImage.srcset = lazyImage.dataset.srcset; | |
| } | |
| lazyImage.classList.remove("lazy"); | |
| lazyImageObserver.unobserve(lazyImage); | |
| } | |
| }); | |
| }); | |
| lazyImages.forEach(function(lazyImage) { | |
| lazyImageObserver.observe(lazyImage); | |
| }); | |
| }); | |
| } else { | |
| var lazyImages = [].slice.call(document.querySelectorAll(".lazy")); | |
| lazyImages.forEach(function(image) { | |
| if(image.dataset.srcset) { | |
| image.srcset = image.dataset.srcset; | |
| } | |
| if(image.dataset.src) { | |
| image.src = image.dataset.src; | |
| } | |
| }); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
P.S. this uses
varfor ie11, but you can useletif you have babel recompile the code