<lazy-image>

<lazy-image>

📖 Docs

<lazy-image> is a custom element that contains an image that has the option to be loaded only on-demand, for performance reasons. If a <lazy-image> is inactive, then its source is not loaded (the XHR won't be made until the active attribute is set on the element). See the code on GitHub.<lazy-image> has the following attributes:
  • active, whether the image should be loaded or not
  • alt, the alternate text for the image the image source (like you would use with a <img>)
  • src, the image source (like you would use with a <img>)
  • srcset, the image source (like you would use with a <img>)

🎬 On-demand loading

For an image to load, it must have the active property set to true. In the example below, the images will only load when clicked (you can check the network tab in your favourite developer tools to see that there's no initial request for these files). This happens because they each start off with the active property set to false, and have a click event listener, that sets it to true:

Code

  <lazy-image src="..." alt="..." id="i"></lazy-image>

  <lazy-image alt="..." srcset="... 1x, ... 2x"></lazy-image>

  <script>
    i.addEventListener('click', function() {
      if (!this.active)
        this.active = true;
    });
  </script>
    
Demo using src

(Click on an image to load it)

sample 1 sample 2 sample 3

Demo using srcset
sample 4

Note:
If you want to have some global setting that controlls all <lazy-image> on the page (i.e. activates or deactivates all of them), you can set the window.LazyImageSiteDefaultActive global before loading the lazy-image.js script.

🎬 Intersection Observer

Intersection observers let you figure out when an element enters into view. Combined with a <lazy-image>, this lets you only load images that are scrolled into view, while leaving images at the bottom of the page that haven't been seen inactive.

Code

  // Create an observer.
  var observer = new IntersectionObserver(onChange, {
    threshold: [0.5]  // rootMargin: '50% 0%'
  });

  // That observes all the random images we've created.
  els.forEach(el => observer.observe(el));

  // Whenever we scroll...
  function onChange(changes) {
    changes.forEach(change => {
      var el = change.target;
      if (!el.active)
        el.active = true;
      observer.unobserve(el);  // Don't care anymore.
    });
  }
IntersectionObserver demo (this demo only works in Chrome, Edge and FF nightly. 👀 caniuse for updates)
random image 19random image 18random image 17random image 16random image 15random image 14random image 13random image 12random image 11random image 10random image 9random image 8random image 7random image 6random image 5random image 4random image 3
 

posted on 2024-04-14 14:49  漫思  阅读(7)  评论(0编辑  收藏  举报

导航