2023-11-05 15:22:15 +01:00

41 lines
1.3 KiB
JavaScript

// 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"));
}