疏影横斜

疏影横斜

有趣有盼,无灾无难.
github
telegram
misskey

Native JS Image Lazy Loading (LazyLoad)

What is Lazy Loading?#

Lazy loading, also known as deferred loading, refers to the practice of delaying the loading of images in a long webpage. It is a great way to optimize webpage performance. Images outside the visible area are not loaded until the user scrolls to them.

What is the purpose of Lazy Loading?#

  • Enhances user experience. If all the images on a page need to be loaded, the waiting time can be long, which significantly impacts user experience.
  • Reduces the loading of unnecessary resources, alleviating server pressure and traffic, and reducing the burden on the browser.
  • Prevents excessive concurrent loading of resources from blocking the loading of JavaScript.

Implementation Principle#

Set the src attribute of the images on the page to an empty string, and set the actual image path in the data-original attribute. When needed, retrieve the value and assign it to the src attribute of the img tag.

Implementation#

<div class="box">
    <img data-original="img/1.jpg">
    <img data-original="img/2.jpg">
    <img data-original="img/3.jpg">
    <img data-original="img/4.jpg">
    <img data-original="img/5.jpg">
    <img data-original="img/6.jpg">
    <img data-original="img/7.jpg">
    <img data-original="img/8.jpg">
    <img data-original="img/9.jpg">
</div>
img{
     display: block;
     margin-bottom: 50px;
     height: 200px;// Make sure to set the image height
}
const imgs = document.getElementsByTagName('img');

function lazyLoad(imgs) {
  // Viewport height
  const clientH = document.documentElement.clientHeight;
  // Scroll distance
  const clientT = document.documentElement.scrollTop || document.body.scrollTop;
  for (let i = 0; i < imgs.length; i++) {
      // If viewport height + scroll distance > distance from image to the top of the browser, load the image
      // !imgs[i].src is to avoid duplicate requests when scrolling back and forth
      if (clientH + clientT > imgs[i].offsetTop && !imgs[i].src) {
          // Custom attributes using data-xx can be retrieved using the dataset.xx of the DOM element
          imgs[i].src = imgs[i].dataset.original;
      }
   }
};

lazyLoad(imgs);
// Listen for scrolling and load the remaining images
window.onscroll = () => lazyLoad(imgs);

Reference#

Lazy Loading - Web Performance | MDN

Lazy Load Images and Video - web.dev

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.