Lazy load images with javascript

Why should you load your images in a lazy way? Among others 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 <img /> 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.

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

lozad

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s