<img data-lazyimage="../../img/unsplash/alex-knight-4NJoYCuWDok-unsplash.jpg" alt="alt tag for the image" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' /%3E">
<img data-lazyimage="{{lazyimage_src}}" alt="{{lazyimage_alt}}" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' /%3E">
{
"lazyimage_src": "../../img/unsplash/alex-knight-4NJoYCuWDok-unsplash.jpg",
"lazyimage_alt": "alt tag for the image"
}
document.addEventListener("DOMContentLoaded", function() {
if ("IntersectionObserver" in window) {
var lazyImages = [].slice.call(document.querySelectorAll("img[data-lazyimage]")); // console.log({lazyImages});
lazyImages.forEach(function(lazyImage) {
lazyImage.classList.add("not-lazyLoaded");
});
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
let loadImage = new Image();
let imgSrc = lazyImage.getAttribute('data-lazyimage'); // console.log({imgSrc});
loadImage.onload = function(){
lazyImage.setAttribute('src',imgSrc);
lazyImage.classList.remove("not-lazyLoaded");
lazyImage.classList.add("lazyLoaded");
};
loadImage.src = imgSrc;
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
});
$lazyimage-timing:0.5s !default;
img[data-lazyimage] {
-webkit-transform:translate3d(0,0,0);
-webkit-backface-visibility:hidden;
-webkit-perspective:1000;
transition:all $lazyimage-timing ease-in-out;
&.not-lazyLoaded {
opacity:0;
}
}
This script is adapted from the Google Developer Web Fundamentals article on lazy loading images and video. The lazy loading of an image in this component is triggered by the presense of the data-lazyimage
attribute of the <img>
tag.