Lazyload observer
by Alexey Zakharov
JavaScript
function LazyLoadImages(params)
{
this.attrName = params.attrName || '';
this.selectorClass = params.selectorClass || '';
this.init();
}
LazyLoadImages.prototype.init = function () {
if (!this.attrName && this.selectorClass)
{
return;
}
var imagesNodes = [].slice.call(document.querySelectorAll('.' + this.selectorClass));
this.watch(imagesNodes, this.selectorClass, this.attrName);
};
LazyLoadImages.prototype.watch = function (imagesNodes, className, attrName) {
if (!attrName && className)
{
return;
}
imagesNodes = [].slice.call(imagesNodes);
if (!imagesNodes.length)
{
return;
}
if ('IntersectionObserver' in window) {
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var image = entry.target;
console.log("lazy loading ", image);
image.src = image.getAttribute(attrName);
image.classList.remove(className);
observer.unobserve(entry.target);
}
});
}, {
rootMargin: '0px 0px 50px 0px'
});
imagesNodes.forEach(function (image) {
return observer.observe(image);
});
} else {
imagesNodes.forEach(function (image) {
return image.src = image.getAttribute(attrName);
});
}
};