Mercurial > hg > index.fcgi > www > www-1
view pics2/lazyload.js @ 82:d7d67887102f
move pinlib to a shared location and have pics use it
author | paulo |
---|---|
date | Wed, 29 Jun 2016 00:11:55 -0700 |
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 }