// credit: https://www.sitepoint.com/five-techniques-lazy-load-images-website-performance/ // create config object: rootMargin and threshold // are two properties exposed by the interface // more information: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API const config = { // margin around the root element defaulting to the viewport rootMargin: '500px 0px 500px 0px', // how much of the image has to be on screen to load the image threshold: 0 }; // register the config object with an instance // of intersectionObserver let observer = new IntersectionObserver(onCloseToVisibleArea, config); window.addEventListener("load", function () { const imgs = document.querySelectorAll('img[data-src]'); imgs.forEach(img => { observer.observe(img); }); }) function onCloseToVisibleArea(entries, self) { // iterate over each entry entries.forEach(entry => { // process just the images that are intersecting. // isIntersecting is a property exposed by the interface if (entry.isIntersecting) { // custom function that copies the path to the img // from data-src to src preloadImage(entry.target); // the image is now in place, stop watching self.unobserve(entry.target); } }); } function preloadImage(imgTag) { imgTag.setAttribute("src", imgTag.getAttribute("data-src")); }