svsticky / pxl

Manage photo albums on S3 buckets
https://pxl-demo.svsticky.nl
Mozilla Public License 2.0
17 stars 2 forks source link

Lazy load images #51

Closed arianvp closed 2 weeks ago

arianvp commented 5 years ago

Using https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

This drastically improves initial load times of albums. and also reduces bandwidth on mobile phones.

I implemented an POC that progressively enhances a page with this in such a way that the page works the same with javascript enabled or disabled. Just when JS is enabled, the page loads faster

POC:

img.lazy {
  display: hidden;
}
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 {
    lazyImages.forEach(function(lazyImage) {
      lazyImage.src = lazyImage.dataset.src;
      lazyImage.classList.remove("lazy");
    });
  }
});
    <a href="/baco-preski-borrel-2017/" class="album">
      <img data-src="https://lol"
           alt="BaCo PreSki Borrel 2017" class="lazy album-cover">
      <noscript><img src="https://lol"
                     alt="BaCo PreSki Borrel 2017" class="album-cover"></noscript>
      <h2 class="album-title">BaCo PreSki Borrel 2017</h2>
    </a>
arianvp commented 5 years ago

opening https://photos.svsticky.nl/ on mobile and clicking on the first album With lazy loading: 65 kilobyte. Opening without lazy loading: 4 MB

SilasPeters commented 2 weeks ago

Was fixed by #90