view pics2/lazyload.js @ 75:ec48011dca1e

pics2: lazy load images in index page
author paulo
date Thu, 11 Feb 2016 00:02:19 -0800
parents
children
line source
1 window.addEventListener('load', lazyLoadImages);
2 window.addEventListener('DOMContentLoaded', lazyLoadImages);
3 window.addEventListener('resize', lazyLoadImages);
4 window.addEventListener('scroll', lazyLoadImages);
6 function lazyLoadImages() {
7 var images = document.getElementsByTagName('img');
8 var loaded = 0;
10 for (var i = 0; i < images.length; i++) {
11 var img = images[i];
12 if (img.hasAttribute('data-src')) {
13 if (isElementInViewport(img)) {
14 img.setAttribute('src', img.getAttribute('data-src'));
15 img.removeAttribute('data-src');
16 }
17 } else {
18 loaded++;
19 }
20 }
22 //console.log('Loaded images:' + loaded + '/' + images.length);
24 if (loaded == images.length) {
25 //console.log('Loaded all images.');
26 window.removeEventListener('load', lazyLoadImages);
27 window.removeEventListener('DOMContentLoaded', lazyLoadImages);
28 window.removeEventListener('resize', lazyLoadImages);
29 window.removeEventListener('scroll', lazyLoadImages);
30 }
31 }
33 function isElementInViewport(el) {
34 var rect = el.getBoundingClientRect();
36 return (
37 rect.top >= 0 &&
38 rect.left >= 0 &&
39 rect.top <= window.innerHeight &&
40 rect.left <= window.innerWidth
41 );
42 }