mediawiki-skins-Citizen/resources/scripts/lazyload.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-08-15 17:40:13 +00:00
/*
* Citizen - Lazyload JS
* https://starcitizen.tools
*
* Lazyloading images with Native API or IntersectionObserver
*/
2020-02-15 23:05:56 +00:00
2020-02-15 23:12:09 +00:00
var observer;
// Native API
2020-02-15 23:05:11 +00:00
if ('loading' in HTMLImageElement.prototype) {
2020-02-15 23:05:56 +00:00
document.querySelectorAll('img.lazy').forEach(function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
2020-02-15 23:05:11 +00:00
2020-02-15 23:05:56 +00:00
if (img.hasAttribute('data-srcset')) {
img.setAttribute('srcset', img.getAttribute('data-srcset'));
}
2020-02-15 23:05:11 +00:00
2020-02-15 23:05:56 +00:00
img.classList.remove('lazy');
});
} else {
2020-02-15 23:05:56 +00:00
// IntersectionObserver API
if (typeof IntersectionObserver !== 'undefined' && 'forEach' in NodeList.prototype) {
2020-02-15 23:12:09 +00:00
observer = new IntersectionObserver(function(changes) {
2020-02-15 23:05:56 +00:00
if ('connection' in navigator && navigator.connection.saveData === true) {
return;
}
2020-02-15 23:05:11 +00:00
2020-02-15 23:05:56 +00:00
changes.forEach(function(change) {
if (change.isIntersecting) {
change.target.setAttribute('src', change.target.getAttribute('data-src'));
2020-02-15 23:05:11 +00:00
2020-02-15 23:05:56 +00:00
if (change.target.hasAttribute('data-srcset')) {
change.target.setAttribute('srcset', change.target.getAttribute('data-srcset'));
}
2020-02-15 23:05:11 +00:00
2020-02-15 23:05:56 +00:00
change.target.classList.remove('lazy');
observer.unobserve(change.target);
}
});
});
document.querySelectorAll('img.lazy').forEach(function(img) {
observer.observe(img);
});
}
2020-02-15 23:05:11 +00:00
}