Advertisement
Igor150195

Ленивая загрузка картинок

Feb 3rd, 2021
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. document.addEventListener("DOMContentLoaded", function() {
  2.     const imageObserver = new IntersectionObserver((entries, imgObserver) => {
  3.         entries.forEach((entry) => {
  4.             if (entry.isIntersecting) {
  5.  
  6.                 const lazyImage = entry.target;
  7.                
  8.                 if (lazyImage.tagName == 'IMG') {
  9.                     lazyImage.src = lazyImage.dataset.src;
  10.                 } else {
  11.                     lazyImage.style.backgroundImage = 'url('+ lazyImage.dataset.src +')';
  12.                 }
  13.                
  14.                 lazyImage.classList.remove("gr_images_lazy_load");
  15.                 imgObserver.unobserve(lazyImage);
  16.             }
  17.         })
  18.     });
  19.     const arr = document.querySelectorAll(".gr_images_lazy_load");
  20.    
  21.     arr.forEach((v) => {
  22.         imageObserver.observe(v);
  23.     })
  24. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement