diff pics3/static/lazyload.js @ 124:9b57b90aea31

initial add for pics3
author paulo
date Thu, 25 Mar 2021 00:33:42 -0700
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/pics3/static/lazyload.js	Thu Mar 25 00:33:42 2021 -0700
     1.3 @@ -0,0 +1,42 @@
     1.4 +window.addEventListener('load', lazyLoadImages);
     1.5 +window.addEventListener('DOMContentLoaded', lazyLoadImages);
     1.6 +window.addEventListener('resize', lazyLoadImages);
     1.7 +window.addEventListener('scroll', lazyLoadImages);
     1.8 +
     1.9 +function lazyLoadImages() {
    1.10 +	var images = document.getElementsByTagName('img');
    1.11 +	var loaded = 0;
    1.12 +
    1.13 +	for (var i = 0; i < images.length; i++) {
    1.14 +		var img = images[i];
    1.15 +		if (img.hasAttribute('data-src')) {
    1.16 +			if (isElementInViewport(img)) {
    1.17 +				img.setAttribute('src', img.getAttribute('data-src'));
    1.18 +				img.removeAttribute('data-src');
    1.19 +			}
    1.20 +		} else {
    1.21 +			loaded++;
    1.22 +		}
    1.23 +	}
    1.24 +
    1.25 +	//console.log('Loaded images:' + loaded + '/' + images.length);
    1.26 +
    1.27 +	if (loaded == images.length) {
    1.28 +		//console.log('Loaded all images.');
    1.29 +		window.removeEventListener('load', lazyLoadImages);
    1.30 +		window.removeEventListener('DOMContentLoaded', lazyLoadImages);
    1.31 +		window.removeEventListener('resize', lazyLoadImages);
    1.32 +		window.removeEventListener('scroll', lazyLoadImages);
    1.33 +	}
    1.34 +}
    1.35 +
    1.36 +function isElementInViewport(el) {
    1.37 +	var rect = el.getBoundingClientRect();
    1.38 +
    1.39 +	return (
    1.40 +		rect.top >= 0 &&
    1.41 +		rect.left >= 0 &&
    1.42 +		rect.top <= window.innerHeight &&
    1.43 +		rect.left <= window.innerWidth
    1.44 +	);
    1.45 +}