javascript lazy load images

Reading Time: 2 minutes

Why should you load your images in a lazy way?

Among other reasons:

  • Increase page speed
  • Better page rank
  • More visitors
  • Reduce bounce rate
  • Increase pages / session rate
  • Improve user experience
  • Reduce infrastructure costs

In a nutshell

This is the process:

  • Modify all your tags by changing src by data-src or something else
  • Add a specific class to every image we want to load lazily.
  • Add a listener to know when the image is being displayed
  • Once the image is displayed, the listener will call our code to modify our image tag
  • The code will get the url from data-src and will update the src property.
  • The image will be loaded by the browser
  • Call the listener after the page loads

Straight to the point

I will use a third-party library called lozad. It’s pretty small and it loads super fast so it won’t have a big impact in your page loading.

From Lozad docs:

“Highly performant, light and configurable lazy loader in pure JS with no dependencies for images, iframes and more, using IntersectionObserver API”

Include the script via CDN in your head tag of your page



<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>

Unfortunately, you cannot use async property here since the script must be loaded before the page loads.

Add this code in your page



<script type="text/javascript">
  // I assume you are using jQuery. Otherwise you can use the classic way
  $(document).ready(() => {
    // to load images in a lazy way
    // lazy loads elements with default selector as '.lozad'
    const observer = lozad();
    observer.observe();
    console.info('lozad observing...');
  });
</script>

Of course you can move this code to a different script file (let say common.js) instead of your page.
You only have to make sure that your file common.js is downloaded and ready to use before lozad call:


const observer = lozad();
observer.observe();

The last step is to modify all your images you want to load lazily.

Before:


<img src="image.jpg" class="yourClass" alt="your image description" />

After:


<img data-src="image.jpg" class="lozad yourClass" alt="your image description" />

You can see more options here https://apoorv.pro/lozad.js/

It’s important you add alt=”your image description” because that text will be displayed while the image is loading. This will give a better user experience to your visitors.

Demo

Resources

Photo by elizabeth lies on Unsplash


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: