banner
meanc

meanc

twitter
github
discord server

Performance Optimization Tool: Lazy Loading

As we all know, there are generally two things for performance optimization: not loading and caching.

Of course, not loading is not feasible, so today let's talk about lazy loading.

In addition to large-scale JavaScript loading, there are other areas we can optimize on the current webpage.

For font file loading, you can refer to my article - Font Module Design.

Image Loading#

Image performance optimization includes many aspects, including compression, format, replacing GIF with video, providing images based on size, using webp, and using CDN.
These are not the focus of today's content. Today, let's take a look at lazy loading images.
The latest browsers have default browser-level lazy loading, which can be enabled using the loading attribute.

<img loading="lazy" />

We can also use the IntersectionObserver object to enable more precise control over lazy loading of images, for example, only showing the image if it appears in the viewport for more than 1 second.

// Get all lazy-loaded image elements
const lazyImages = document.querySelectorAll(".lazy-loaded-image");

// Set options for IntersectionObserver
const options = {
  root: null,
  rootMargin: "0px",
  threshold: 0.5
};

// Create IntersectionObserver object
const lazyImageObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
      // If the image appears in the viewport for more than 1 second, start loading the image
      setTimeout(() => {
        const lazyImage = entry.target;
        lazyImage.src = lazyImage.dataset.src;
        lazyImage.classList.remove("lazy");
        lazyImageObserver.unobserve(lazyImage);
      }, 1000);
    }
  });
}, options);

// Observe all lazy-loaded image elements
lazyImages.forEach((lazyImage) => {
  lazyImageObserver.observe(lazyImage);
});

Images in CSS Files#

The above loading method cannot be used for images in CSS files, but we can still use viewport monitoring to dynamically add class names to achieve lazy loading of images.

.lazy-background {  background-image: url("hero-placeholder.jpg");
/* Placeholder image */}
.lazy-background.visible {  background-image: url("hero.jpg"); 
/* The final image */}

By modifying the code above and replacing the content in setTimeout with the following (make corresponding changes to other code):

  lazyBackGround.classList.add("visible");

we can dynamically change the way images are loaded in CSS to achieve lazy loading.

Lazy Loading of Videos#

Videos do not have the lazy attribute, but they have the preload attribute that can be used.

<video controls preload="none" poster="one-does-not-simply-placeholder.jpg">  <source src="one-does-not-simply.webm" type="video/webm">  <source src="one-does-not-simply.mp4" type="video/mp4"></video>

The poster attribute is very useful as it can be used to display an image as a placeholder.

As mentioned earlier, we can use videos to replace GIFs because videos have a significant advantage in terms of file size compared to GIFs.

In this scenario, our video tag looks like this:
This is a lazy loading video that plays automatically and loops continuously.

<video class="lazy" autoplay muted loop playsinline width="610" height="254" poster="one-does-not-simply.jpg">  <source data-src="one-does-not-simply.webm" type="video/webm">  <source data-src="one-does-not-simply.mp4" type="video/mp4"></video>

We can still use IntersectionObserver to dynamically replace the src of the source elements to achieve fine-grained control over lazy loading.

if (video.isIntersecting) {

for (var source in video.target.children) {

var videoSource = video.target.children[source];

if (

typeof videoSource.tagName === 'string' &&

videoSource.tagName === 'SOURCE'

) {

videoSource.src = videoSource.dataset.src;

}

}

video.target.load();

video.target.classList.remove('lazy');

lazyVideoObserver.unobserve(video.target);

}

Lazy Loading of iframes#

iframes also support loading=lazy. The simplest method is to add it directly to the tag, which is very effective for scenarios where a large number of videos are embedded in the page.

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