Mercurial > hg > index.fcgi > www > www-1
annotate pics3/static/lazyload.js @ 144:90f3021e3137
myrss2: FEEDS: Remove longform.org; add propublic.org
author | paulo |
---|---|
date | Tue, 28 May 2024 06:23:58 +0000 |
parents | |
children |
rev | line source |
---|---|
paulo@124 | 1 window.addEventListener('load', lazyLoadImages); |
paulo@124 | 2 window.addEventListener('DOMContentLoaded', lazyLoadImages); |
paulo@124 | 3 window.addEventListener('resize', lazyLoadImages); |
paulo@124 | 4 window.addEventListener('scroll', lazyLoadImages); |
paulo@124 | 5 |
paulo@124 | 6 function lazyLoadImages() { |
paulo@124 | 7 var images = document.getElementsByTagName('img'); |
paulo@124 | 8 var loaded = 0; |
paulo@124 | 9 |
paulo@124 | 10 for (var i = 0; i < images.length; i++) { |
paulo@124 | 11 var img = images[i]; |
paulo@124 | 12 if (img.hasAttribute('data-src')) { |
paulo@124 | 13 if (isElementInViewport(img)) { |
paulo@124 | 14 img.setAttribute('src', img.getAttribute('data-src')); |
paulo@124 | 15 img.removeAttribute('data-src'); |
paulo@124 | 16 } |
paulo@124 | 17 } else { |
paulo@124 | 18 loaded++; |
paulo@124 | 19 } |
paulo@124 | 20 } |
paulo@124 | 21 |
paulo@124 | 22 //console.log('Loaded images:' + loaded + '/' + images.length); |
paulo@124 | 23 |
paulo@124 | 24 if (loaded == images.length) { |
paulo@124 | 25 //console.log('Loaded all images.'); |
paulo@124 | 26 window.removeEventListener('load', lazyLoadImages); |
paulo@124 | 27 window.removeEventListener('DOMContentLoaded', lazyLoadImages); |
paulo@124 | 28 window.removeEventListener('resize', lazyLoadImages); |
paulo@124 | 29 window.removeEventListener('scroll', lazyLoadImages); |
paulo@124 | 30 } |
paulo@124 | 31 } |
paulo@124 | 32 |
paulo@124 | 33 function isElementInViewport(el) { |
paulo@124 | 34 var rect = el.getBoundingClientRect(); |
paulo@124 | 35 |
paulo@124 | 36 return ( |
paulo@124 | 37 rect.top >= 0 && |
paulo@124 | 38 rect.left >= 0 && |
paulo@124 | 39 rect.top <= window.innerHeight && |
paulo@124 | 40 rect.left <= window.innerWidth |
paulo@124 | 41 ); |
paulo@124 | 42 } |