Web Resources - Lazy Loading

> (World Wide) Web - (W3|WWW) > Web - Browser

1 - About

A Lazy loading method will fetch only the visible resource (image, advertisements) in the web browser window

Lazy loading is technique that defers loading of non-critical resources at page load time. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, “non-critical” is often synonymous with “off-screen”.

Advertising

3 - Solutions

Solutions for detecting if an element is visible in the viewport (in order to lazy-load its content)

3.1 - Dom API

Solutions have often listened for scroll or resize events, then used DOM APIs like getBoundingClientRect() to calculate where elements are relative to the viewport. This works, but is not efficient. It have been error-prone, often causing the browser to become sluggish.

3.2 - Web Api: IntersectionObserver

IntersectionObserver is a browser API that allows us to efficiently detect when an observed element enters or exits the browser's viewport.

4 - Example

4.1 - Image and video

Library for image and video:

Example from Lazy Loading Images and Video after the DOMContentLoaded event.

<img class="lazy" src="placeholder-image.jpg" data-src="image-to-lazy-load-1x.jpg" data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x" alt="I'm an image!">
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.srcset = lazyImage.dataset.srcset;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });
 
    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Possibly fall back to a more compatible method here
  }
});

More … https://webpack.js.org/guides/lazy-loading/

Advertising

4.2 - Ads

5 - Library

6 - Documentation