You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.8 KiB
JavaScript

function createImageLoader(settings) {
var loadImageByUrl = function(target) {
target.addEventListener("load", function() {
target.style.opacity = 1;
});
target.setAttribute("src", target.getAttribute("data-src"));
};
var lazyloader = createLazyloader();
lazyloader();
function throttle(fn, delay, atleast) {
var timeout = null,
startTime = new Date();
return function() {
var curTime = new Date();
clearTimeout(timeout);
if (curTime - startTime >= atleast) {
fn();
startTime = curTime;
} else {
timeout = setTimeout(fn, delay);
}
}
}
function getOffset(el) {
var box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - document.documentElement.clientTop,
left: box.left + window.pageXOffset - document.documentElement.clientLeft
};
}
function createLazyloader() {
var lazyImageList = $('img[loader=lazy]');
lazyImageList.each(function(index, element) {
element.style.opacity = 0;
element.style.transition = "opacity 0.5s ease-in-out";
});
return function() {
var seeHeight = window.innerHeight;
var scrollTop =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
lazyImageList = lazyImageList.filter(function(index, element) {
var offsetTop = $(element).offset().top;
var hasVisible = offsetTop < seeHeight + scrollTop;
if (hasVisible) {
loadImageByUrl(element);
}
return !hasVisible;
});
}
}
if (window.addEventListener) {
window.addEventListener('scroll', throttle(lazyloader, 500, 500), false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', throttle(lazyloader, 500, 500));
}
}