paulo@75: window.addEventListener('load', lazyLoadImages); paulo@75: window.addEventListener('DOMContentLoaded', lazyLoadImages); paulo@75: window.addEventListener('resize', lazyLoadImages); paulo@75: window.addEventListener('scroll', lazyLoadImages); paulo@75: paulo@75: function lazyLoadImages() { paulo@75: var images = document.getElementsByTagName('img'); paulo@75: var loaded = 0; paulo@75: paulo@75: for (var i = 0; i < images.length; i++) { paulo@75: var img = images[i]; paulo@75: if (img.hasAttribute('data-src')) { paulo@75: if (isElementInViewport(img)) { paulo@75: img.setAttribute('src', img.getAttribute('data-src')); paulo@75: img.removeAttribute('data-src'); paulo@75: } paulo@75: } else { paulo@75: loaded++; paulo@75: } paulo@75: } paulo@75: paulo@75: //console.log('Loaded images:' + loaded + '/' + images.length); paulo@75: paulo@75: if (loaded == images.length) { paulo@75: //console.log('Loaded all images.'); paulo@75: window.removeEventListener('load', lazyLoadImages); paulo@75: window.removeEventListener('DOMContentLoaded', lazyLoadImages); paulo@75: window.removeEventListener('resize', lazyLoadImages); paulo@75: window.removeEventListener('scroll', lazyLoadImages); paulo@75: } paulo@75: } paulo@75: paulo@75: function isElementInViewport(el) { paulo@75: var rect = el.getBoundingClientRect(); paulo@75: paulo@75: return ( paulo@75: rect.top >= 0 && paulo@75: rect.left >= 0 && paulo@75: rect.top <= window.innerHeight && paulo@75: rect.left <= window.innerWidth paulo@75: ); paulo@75: }