6

I have the following lazy load function which works for <img>.

<script>
        document.addEventListener("DOMContentLoaded", function() {
          var lazyloadImages;    

          if ("IntersectionObserver" in window) {
            lazyloadImages = document.querySelectorAll(".lazy");
            var imageObserver = new IntersectionObserver(function(entries, observer) {
              entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                  var image = entry.target;
                  image.src = image.dataset.src;
                  image.classList.remove("lazy");
                  imageObserver.unobserve(image);
                }
              });
            });

            lazyloadImages.forEach(function(image) {
              imageObserver.observe(image);
            });
          } else {  
            var lazyloadThrottleTimeout;
            lazyloadImages = document.querySelectorAll(".lazy");
            
            function lazyload () {
              if(lazyloadThrottleTimeout) {
                clearTimeout(lazyloadThrottleTimeout);
              }    

              lazyloadThrottleTimeout = setTimeout(function() {
                var scrollTop = window.pageYOffset;
                lazyloadImages.forEach(function(img) {
                    if(img.offsetTop < (window.innerHeight + scrollTop)) {
                      img.src = img.dataset.src;
                      img.classList.remove('lazy');
                    }
                });
                if(lazyloadImages.length == 0) { 
                  document.removeEventListener("scroll", lazyload);
                  window.removeEventListener("resize", lazyload);
                  window.removeEventListener("orientationChange", lazyload);
                }
              }, 20);
            }

            document.addEventListener("scroll", lazyload);
            window.addEventListener("resize", lazyload);
            window.addEventListener("orientationChange", lazyload);
          }
        })
    </script>

The function isn't mine and I need to know how to modify it to work for the next example which load images from CSS:

<div class="col-md-2 col-sm-3 col-xs-4 photo" style="padding: 2.5px">
    <span onclick="window.location.href=\''.$link.'\';" 
        class="thumbnail" 
        role="img" 
        style="background-image: url(\''.$image.'\'); cursor: pointer; margin: 0; margin-top: 5px;" 
        aria-label="' . $row["topic_title"] . '"
        title="'.$row['topic_title'].'">
    </span>
    
    <center>
        <p class="name" style="margin 0 2px; color: white; margin-top: 5px;">
            <a href="'.$link.'" title="'.$row['topic_title'].'">' . $title . '</a>
        </p>
    </center>
</div>

On a page with 24 gifs, the page loads relatively slow and I'd like to change that. I could load the images as normal using <img>, but I want the page to be more dynamic because using span I have different temathic.

Here is how I managed to do the script and it works correctly. Hope someone will find it useful.

if (entry.isIntersecting) {
    var image = entry.target;
    image.src = image.dataset.src;      
    var imageUrl = "url" + "(" + "'" + image.src + "')";
    entry.target.style.backgroundImage = imageUrl;
    image.classList.remove("lazy");
    imageObserver.unobserve(image);
}

1
  • Side-note: for <img /> you don't need any scripts - just use loading="lazy" - all major browsers added support for it about 1-2 years ago, see here: stackoverflow.com/a/60405256/159145 Commented Apr 30, 2021 at 17:10

1 Answer 1

0

On a page with 24 gifs, the page loads relatively slow and I'd like to change that.

Images in general are really heavy on websites. That's most likely whats slowing the site down. If your website needs that many GIFs I would firstly look at compression techniques. Search for GIF to WebP converters and file compressors (ImageAlpha, ImageOptim, Handbrake to name a few).

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.