Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const LazyLoader = (function () {
  2.     let module = {};
  3.  
  4.     module.init = function () {
  5.         document.addEventListener("DOMContentLoaded", function() {
  6.             let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
  7.  
  8.             if ("IntersectionObserver" in window) {
  9.                 let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
  10.                     entries.forEach(function(entry) {
  11.                         if (entry.isIntersecting) {
  12.                             let lazyImage = entry.target;
  13.                             lazyImage.src = lazyImage.dataset.src;
  14.                             lazyImage.classList.remove("lazy");
  15.                             lazyImageObserver.unobserve(lazyImage);
  16.                         }
  17.                     });
  18.                 });
  19.  
  20.                 lazyImages.forEach(function(lazyImage) {
  21.                     lazyImageObserver.observe(lazyImage);
  22.                 });
  23.             } else {
  24.                 _processImages(lazyImages);
  25.  
  26.                 document.addEventListener('scroll', function () {
  27.                     _processImages(lazyImages);
  28.                 })
  29.             }
  30.         });
  31.     };
  32.  
  33.     let _processImages = function(lazyImages) {
  34.         [].forEach.call(lazyImages, function (image) {
  35.             if (_imageOnScreen(image) && image.classList.contains('lazy')) {
  36.                 _loadImage(image);
  37.             }
  38.         });
  39.     };
  40.  
  41.     let _loadImage = function(image) {
  42.         image.src = image.dataset.src;
  43.         image.classList.remove('lazy');
  44.     };
  45.  
  46.     let _imageOnScreen = function(image) {
  47.         let rect = image.getBoundingClientRect();
  48.         let viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  49.         return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
  50.     };
  51.  
  52.     return module;
  53. })();
  54.  
  55. export {LazyLoader};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement