Search code examples
laraveljquery-lazyload

have error with tuupola/lazyload in laravel app


In Laravel 7 / blade / bootstrap 4.1.2 / jquery 3.3.1 I want to apply lazyload for my images with https://github.com/tuupola/lazyload

I selected 4 big files(3 png, 1 jpg 3-10 MiB) and show them in blade template :

<div class="row">
    @foreach($bigImages as $nextBigImage)
        <div class="col-12 m-2 p-2 lazy_image">
            <img src="/images/big/{{ $nextBigImage }}" title= "{{ $nextBigImage }}" style="width: 100% !important;">
        </div>
    @endforeach
</div>

and on js init :

let images = document.querySelectorAll(".lazy_image");
console.log('images::')
console.log(images)

new LazyLoad(images, {
    root: null,
    rootMargin: "0px",
    threshold: 0
});

As a result I have an error in my JS-console

http://local-votes.com/null 404 (Not Found)

where http://local-votes.com is my local host I see in the console : https://i.sstatic.net/5Moy7.jpg

If to scroll browser down I have 1 more error in browser's console. How to fix it ?

Thanks!


Solution

  • If you want try this.

    in your html file

    <img src="defaul.jpg" data-src="main.jpg" alt="img" class="lazy">
    

    on your js file or internal document.addEventListener("DOMContentLoaded", function() { var 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 {
        // Possibly fall back to a more compatible method here
      }
    });
    

    i recomend you to visit https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video