function createImageLoader(settings) { var loadImageByUrl = function(target) { target.addEventListener("load", function() { target.style.opacity = 1; }); target.setAttribute("src", target.getAttribute("data-src")); }; if (!Array.from) { return function from(arrayLike) { console.info(arrayLike); return [].slice.call(arrayLike) } } var imageList = [].slice.call(document.querySelectorAll('img[loader=ready]')); imageList.forEach(function(element, index) { element.style.opacity = 0; element.style.transition = "opacity 0.5s ease-in-out"; loadImageByUrl(element); }); 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 = [].slice.call(document.querySelectorAll('img[loader=lazy]')); lazyImageList.forEach(function(element, index) { 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(element, index) { var offsetTop = getOffset(element).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)); } }