view pics2/lazyload.js @ 140:ae6b4032a912

myrss2: FEEDS: Add jabberwocking.com, remove danielmiessler.com
author paulo
date Mon, 03 Jul 2023 04:40:23 +0000
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 }