Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How lazy loading images using JavaScript works?

I am curious about how lazy loading images, images that will be loaded when scrolled to them, works.

Any hint?

like image 386
xiaohan2012 Avatar asked Mar 12 '12 13:03

xiaohan2012


People also ask

How lazy loading works in JavaScript?

Native lazy loading API Lazy loading is built on top of the Intersection Observer API, which is a browser API that provides a way of detecting or knowing when an element called a target, a parent element, or becomes available or visible inside the browsers viewport, as the case may be.

Can I use lazy loading images?

Using browser-level lazy-loading #This attribute can be added to <img> elements, and also to <iframe> elements. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them. Note <iframe loading="lazy"> is currently non-standard.

How do you test for lazy loading images?

If you want to test the execution of lazy loading, I can recommend that you clear your browser's cache and try reloading. In Chrome's Developer Console (F12), you can tweak the speeds and simulate modem speeds. Hit F12 -> Network tab -> Change the "No throttling" dropdown . Choose a slower speed to experiment.

What is lazy loading and how do you achieve it?

Lazy loading is the practice of delaying load or initialization of resources or objects until they're actually needed to improve performance and save system resources.


1 Answers

2021 - keep it simple...

Lots of plugin recommendations here, and depending on your use case those may be valuable to you.

If you can't be bothered to write this short snippet of code below, or you need callbacks already built out then you can use this plugin I built which is based on this exact answer and only 0.5kb when minified. My plugin, Simply Lazy, can even work with IE if you simply add a polyfill.

At the end of the day if you just need to lazy load some images then it's as simple as:

<img data-src="your-image-path-here" class="lazyload" />

And:

let observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(function (entry) {
    if (entry.intersectionRatio > 0 || entry.isIntersecting) {
      const image = entry.target;
      observer.unobserve(image);

      if (image.hasAttribute('src')) {
        // Image has been loaded already
        return;
      }

      // Image has not been loaded so load it
      const sourceUrl = image.getAttribute('data-src');
      image.setAttribute('src', sourceUrl);

      image.onload = () => {
        // Do stuff
      }

      // Removing the observer
      observer.unobserve(image);
    }
  });
});

document.querySelectorAll('.lazyload').forEach((el) => {
  observer.observe(el);
});

Using the Intersection Observer API makes this all very simple. You can also use it within the shadowRoot and it works fine there as well.

I've also found this article helpful to understand what is going on here.

like image 150
maxshuty Avatar answered Oct 06 '22 01:10

maxshuty