Mercurial > hg > index.fcgi > www > www-1
comparison pics2/lazyload.js @ 130:06f97e38e1b2
pics3: add pin support
author | paulo |
---|---|
date | Thu, 20 Jan 2022 00:40:14 -0800 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:1257315e6e76 |
---|---|
1 window.addEventListener('load', lazyLoadImages); | |
2 window.addEventListener('DOMContentLoaded', lazyLoadImages); | |
3 window.addEventListener('resize', lazyLoadImages); | |
4 window.addEventListener('scroll', lazyLoadImages); | |
5 | |
6 function lazyLoadImages() { | |
7 var images = document.getElementsByTagName('img'); | |
8 var loaded = 0; | |
9 | |
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 } | |
21 | |
22 //console.log('Loaded images:' + loaded + '/' + images.length); | |
23 | |
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 } | |
32 | |
33 function isElementInViewport(el) { | |
34 var rect = el.getBoundingClientRect(); | |
35 | |
36 return ( | |
37 rect.top >= 0 && | |
38 rect.left >= 0 && | |
39 rect.top <= window.innerHeight && | |
40 rect.left <= window.innerWidth | |
41 ); | |
42 } |