Cloudinary Blog

Lazy-Loading JavaScript for High-Speed Webpage Performance

 Lazy-Loading JavaScript for High-Speed Webpage Performance

JavaScript is a popular programming language, typically for building interactive web apps, thanks to its ease of use and ability to run in any browser with no "JavaScript turned off" setting. The language is easy to learn, accelerating app development. However, to avoid performance issues, be sure to optimize your JavaScript apps for media loading. You can do that by adopting techniques for optimizing website images, such as lazy loading.

This post addresses the following topics:

What Is JavaScript?

JavaScript (JS) is multiparadigm, i.e., ideal for procedural, functional, and object-oriented programming. Originally designed for the client side only, JS is increasingly being used on the server side as the back-end for websites and web apps through frameworks, such as Node.js.

Why Are JavaScript Libraries Widely Used?

For efficiency, in addition to using libraries when developing back-end APIs, many JS programmers leverage frameworks, which offer convenient shortcuts for common capabilities and methods. Frameworks help standardize programming and can significantly boost productivity.

Part of what makes frameworks easy to use in JS is its huge user base, which works with many tools. The most popular frameworks have extensive documentation, robust communities, lots of illuminating dialog on implementation, and tips and suggestions for best practices. Additionally, strong community support means that bugs and security issues tend to be found and fixed quickly.

What Is Lazy Loading?

Lazy loading is a practice that delays the initialization of web elements, e.g., you can prevent a video at the bottom of a page from loading until the viewer has clicked the Play button or scrolled over there.

Lazy loading improves web performance and can help you avoid the following pitfalls:

  • Page lag created by multiple synchronous requests for content.
  • Longer load times due to large content files.
  • Loss of users due to poor site performance, which is especially problematic in case of slow Internet connections.
  • Bandwidth waste caused by loaded but unviewed content.

To head off those issues, most modern browsers support lazy loading. Notably, Google Chrome 76 and higher support lazy loading natively with a loading attribute that enables you to defer loading of offscreen images with no additional code. For browsers in which lazy loading doesn’t work, you can often implement it by means of libraries or polyfills with an associated API.

What Is the Intersection Observer API?

The Intersection Observer API is a built-in browser tool for manipulating elements on websites and in applications by asynchronously monitoring the intersection of elements with the viewer’s viewport or other elements. With that API, you can—

  • Lazy-load content as the viewer scrolls through your page.
  • Implement “infinite scrolling,” such as that in Instagram and many forums.
  • Determine and report on the visibility of ads for revenue analysis or user-experience studies.
  • Reduce resource consumption by withholding tasks or animations until they are relevant for the viewer.

To use Intersection Observer, first create a callback, which can be triggered by an element that intersects with a specified element or the viewport. Often, the intersection is with an element’s closest scrollable ancestor. The following code shows a callback with options for intersection elements.

Copy to clipboard
let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

When defining this intersection, you can specify the overlap, i.e., how close the content is to being accessed. Alternatively, trigger it the first time an event, such as a button click, occurs.

Can You Simplify the Lazy-Loading Process?

You can simplify lazy loading with libraries. Below are two examples.

  • Lozad.js is an open-source, lightweight library for configuring lazy loading of images, iframes, video, and audio. Based on the Intersection Observer API, Lozad.js adds no dependencies to your projects. You can use it with either static or dynamically loaded elements.

    To install Lozad.js, type:

    Copy to clipboard
    $ npm install --save lozad

    or:

    Copy to clipboard
    $ yarn add lozad
  • Yall.js is also an open-source library for configuring lazy loading of various media, including <img>, <picture>, <video>, and <iframe> elements; and CSS background images. Yall.js works with not only JS but also with the <noscript> tag. Based on the Intersection Observer API, Yall.js can monitor changes in the Document Object Model (DOM) with Mutation Observer.

    To install Yall.js, type:

    Copy to clipboard
    npm install yall-js

How Do You Lazy-Load in JavaScript with Intersection Observer?

Below is a simplified tutorial on how to implement lazy loading with Intersection Observer. For more details, see the full tutorial by Chidume Nnamdi.

  1. Define the `image` tag with lazy-load attributes.

    Define the `image` tag with a shared class that identifies lazy-loaded images, e.g., `lzy_img`. That tag must contain two attributes:

    • The regular `src` attribute, which refers to the original image.
    • The `data-src` attribute, which refers to the image shown after lazy loading.
    See this example:
    Copy to clipboard
    <img class="lzy_img" src="lazy_img.jpg" data-src="real_img.jpg" />
    
  2. Instantiate Intersection Observer.

    First, create an instance of the Intersection Observer with two arguments: an array of elements shown in the browser’s viewport and an imageObserver instance.

    Next, loop through entries and perform lazy loading on each of them. For each entry, check if it is intersecting with the viewport, i.e., if it is currently displayed there. If so, set the src attribute to the value of the data-src attribute.

    See this example:

    Copy to clipboard
    const imageObserver = new IntersectionObserver((entries, imgObserver) => {
    entries.forEach((entry) => {
        if(entry.isIntersecting) {
            const lazyImage = entry.target
            lazyImage.src = lazyImage.dataset.src
        }
    });
  3. Observe and lazy-load images with ImageObserver.

    Call imageObserver and pass to it all the image elements in the document with document.querySelectorAll('img.lzy_img'). imageObserver listens on the images to detect when they intersect with the browser viewport.

    Copy to clipboard
    imageObserver.observe(document.querySelectorAll('img.lzy_img'));
  4. Verify that lazy loading works.

    Create a few initial images and real images for lazy loading and then create an index.html file that includes the image tags in step 1. Space out the images so that some of them will initially be outside the viewport.

    Here’s an example of a configured image tag:

    Copy to clipboard
    <img class="lzy_img" src="lazy_img.jpg" data-src="img_1.jpg" />

    Within the index.html file, run a script with Intersection Observer and imageObserver, as in the following example.

    Copy to clipboard
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const imageObserver = new IntersectionObserver((entries, imgObserver) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        const lazyImage = entry.target
                        console.log("lazy loading ", lazyImage)
                        lazyImage.src = lazyImage.dataset.src
                    }
                })
            });
            const arr = document.querySelectorAll('img.lzy_img')
            arr.forEach((v) => {
                imageObserver.observe(v);
            })
        })
    </script>

    Place the files on a web server and test them on a web browser.

How Do You Lazy-Load With Cloudinary?

Cloudinary is a cloud-based service that simplifies and automates the process of manipulating, optimizing, and delivering images and videos, optimized for any device at any bandwidth. Those capabilities are offered through the Cloudinary JavaScript SDK, which you can seamlessly integrate with your JS apps.

Hearteningly, lazy loading now works in all modern browsers, meaning that you can lazy-load media by merely adding the loading option to the Cloudinary SDK’s image tag (cl.imageTag), like this:

Copy to clipboard
let img = cl.imageTag('sample.jpg', {width: 300, crop: "scale", loading: "lazy"}).toHtml();

Afterwards, reduce the image size as much as possible to accelerate page loading by adopting one or more of the following Cloudinary features:

  • Smart quality optimization, which automatically compresses images without sacrificing quality. Just add q_auto to your URLs, as explained in this post.
  • Automated file formatting, which serves the correct file format for your browser. Just add f_auto to your URLs. For details, see this post.
  • Progressive image optimization, which renders images with the correct method. You have four options: nonprogressive, steep-progressive, semiprogressive, and default progressive (fl_progressive). Refer to this post for the particulars.

Why not try out all that magic? Start with signing up for a free Cloudinary account. We offer generous free plans to get you started.

Want to Learn More About Lazy-Loading?

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more