annotate pics2/lazyload.js @ 125:d216dd8e63da

pics3: implement thumbs page
author paulo
date Sat, 01 May 2021 01:59:08 -0700
parents
children
rev   line source
paulo@75 1 window.addEventListener('load', lazyLoadImages);
paulo@75 2 window.addEventListener('DOMContentLoaded', lazyLoadImages);
paulo@75 3 window.addEventListener('resize', lazyLoadImages);
paulo@75 4 window.addEventListener('scroll', lazyLoadImages);
paulo@75 5
paulo@75 6 function lazyLoadImages() {
paulo@75 7 var images = document.getElementsByTagName('img');
paulo@75 8 var loaded = 0;
paulo@75 9
paulo@75 10 for (var i = 0; i < images.length; i++) {
paulo@75 11 var img = images[i];
paulo@75 12 if (img.hasAttribute('data-src')) {
paulo@75 13 if (isElementInViewport(img)) {
paulo@75 14 img.setAttribute('src', img.getAttribute('data-src'));
paulo@75 15 img.removeAttribute('data-src');
paulo@75 16 }
paulo@75 17 } else {
paulo@75 18 loaded++;
paulo@75 19 }
paulo@75 20 }
paulo@75 21
paulo@75 22 //console.log('Loaded images:' + loaded + '/' + images.length);
paulo@75 23
paulo@75 24 if (loaded == images.length) {
paulo@75 25 //console.log('Loaded all images.');
paulo@75 26 window.removeEventListener('load', lazyLoadImages);
paulo@75 27 window.removeEventListener('DOMContentLoaded', lazyLoadImages);
paulo@75 28 window.removeEventListener('resize', lazyLoadImages);
paulo@75 29 window.removeEventListener('scroll', lazyLoadImages);
paulo@75 30 }
paulo@75 31 }
paulo@75 32
paulo@75 33 function isElementInViewport(el) {
paulo@75 34 var rect = el.getBoundingClientRect();
paulo@75 35
paulo@75 36 return (
paulo@75 37 rect.top >= 0 &&
paulo@75 38 rect.left >= 0 &&
paulo@75 39 rect.top <= window.innerHeight &&
paulo@75 40 rect.left <= window.innerWidth
paulo@75 41 );
paulo@75 42 }