Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const LazyLoader = (function () {
- let module = {};
- module.init = function () {
- document.addEventListener("DOMContentLoaded", function() {
- let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
- if ("IntersectionObserver" in window) {
- let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
- entries.forEach(function(entry) {
- if (entry.isIntersecting) {
- let lazyImage = entry.target;
- lazyImage.src = lazyImage.dataset.src;
- lazyImage.classList.remove("lazy");
- lazyImageObserver.unobserve(lazyImage);
- }
- });
- });
- lazyImages.forEach(function(lazyImage) {
- lazyImageObserver.observe(lazyImage);
- });
- } else {
- _processImages(lazyImages);
- document.addEventListener('scroll', function () {
- _processImages(lazyImages);
- })
- }
- });
- };
- let _processImages = function(lazyImages) {
- [].forEach.call(lazyImages, function (image) {
- if (_imageOnScreen(image) && image.classList.contains('lazy')) {
- _loadImage(image);
- }
- });
- };
- let _loadImage = function(image) {
- image.src = image.dataset.src;
- image.classList.remove('lazy');
- };
- let _imageOnScreen = function(image) {
- let rect = image.getBoundingClientRect();
- let viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
- return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
- };
- return module;
- })();
- export {LazyLoader};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement