Cloudinary Blog

Lazy Loading: Choosing the Best Option

Lazy Loading: Choosing the Best Option

In today’s digital-first age, online site performance is critical for ensuring business continuity, attracting repeat sales, and gaining a competitive advantage. Lazy loading accelerates performance for websites and apps. Many implementation techniques are available, however, so choose wisely. In particular, become familiar with the universal practices and the language- and framework-specific approaches.

This article covers the following topics:

Lazy Loading Defined

What’s lazy loading in web development? That’s an approach through which you can prioritize content, delaying loads for less relevant or visible content. Consequently, your apps or websites load faster, delivering an enhanced user experience.

Typically, you enable lazy loading by programming content to load only when it’s being viewed or when it’s soon to appear as the user scrolls down. If the user does not scroll down or the content never approaches the viewport, ensure that no loading occurs.

Advantages

Lazy loading affords you and your users two major benefits:

  • Performance improvement. With lazy loading, you use only the resources for the relevant content, eliminating unnecessary content requests, reducing the processing power for content rendering, and loading your site faster.
  • Cost reduction. Since content is delivered only when needed, you save bandwidth, and your content server spends less time processing requests. Concurrently, you reduce resource costs, particularly if you pay on a per-use basis.

Lazy Loading in Three Common Frameworks

The easiest way to implement lazy loading is through frameworks and libraries. Below are the three most common ones.

React

The React framework includes two components for lazy loading:

  • React.Suspense, with which you can specify when to render the lower-level components. Use it to wrap lazy components and to define when to trigger event loads.
  • React.lazy, with which you can dynamically load content by splitting code between components and granularly defining which parts of a component to load first.

The related code reads like this:

Copy to clipboard
import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
 return (
  <div>
   <Suspense fallback={<div>Loading...</div>}>
    <OtherComponent />
   </Suspense>
  </div>
 );
}

For more details, see the post Lazy-Load React and Boost Page Performance for Your Apps.

JavaScript

You can implement lazy loading in JavaScript (JS) with the native Intersection Observer API or with lazy-loading libraries, such as Lozad and Yall.

Intersection Observer API

With the Interaction Observer API, you can asynchronously monitor how page elements intersect with the other elements or the user’s viewport, leveraging those events as triggers to load elements.

For example, you can lazy-load as the user scrolls down your page, collect metrics on user experience or ad visibility, enforce “infinite scrolling,” and withhold resources until the user requests them.

Lozad.js

Lozad.js, an open-source library based on Intersection Observer, can lazy-load media with both dynamic and static elements. You can easily add the library to your JS files with no dependencies.

Yall.js

Yall.js, another open-source library based on Intersection Observer, can lazy-load media, CSS background images, and <noscript> elements. Additionally, with this library, you can monitor changes to the Document Object Model (DOM) for dynamically added elements along with Mutation Observer.

Angular

The Angular framework offers built-in support for lazy loading with the --route flag, which you add to your modules and define with loadChildren your loading preference. See this example:

Copy to clipboard
const routes: Routes = [
 {
  path: 'customers',
  loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
 }
];

Angular also supports several packages for lazy loading, including these two:

  • ngx-loadable, an open-source package with an API for loading indicators, contains the ngx-loadable component, with which you wrap modules; and the LoadableService service, with which you load them as desired.
  • hero-loader, an open-source package for lazy-loading modules according to triggers like route changes, clicks, or mouseovers. This package extends the capabilities of the native loadChildren method.

For more details, see the article How to Get Killer Page Performance With Angular Lazy Loading.

Tips and Tricks

When implementing lazy loading, consider adopting the following tips to sidestep trigger delays and content shifting, also to avoid abusing lazy-loading capabilities.

Add Buffer Time for Image Loads

If users scroll too quickly through your page or the connection is throttled, your lazy content might not load before the placeholders hit the viewport. That means that users end up waiting for content to load or never see it.

To avoid that scenario, consider triggering loads slightly before content is requested, e.g., when it comes within 500 pixels of the viewport. Such a setup would allow a little extra time for the content to load before the user sees it without significantly impacting performance.

Add buffer time with Intersection Observer by increasing the size of your bounding box, which is defined by the root and rootMargin parameters. You can also set your event listener to trigger if the difference between your element and the viewport edge exceeds zero.

Avoid Content Shifting With Lazy Loading

If your site contains responsive or dynamic content and the size of your element placeholders differ from that of your loaded elements, your content might shift and, while the elements are loading, bump the content users are viewing, decimating the user experience. If loading is delayed or if it fails, content shifts can also negatively affect site appearance.

The best way to avoid content shifts is to define your element container with the loaded component’s height and width, ensuring that when your page initially renders, all the elements are in their final position as they load.

Do Not Lazy-Load All the Images

For all that it’s tempting to lazy-load all your images, that’s a bad idea since no images load until your JS code executes. The result? Loading of the images at the top of your page might be delayed or might fail entirely.

A good strategy is to automatically load the content that users see when they first visit your page. Be sure to account for the differences between standard screen sizes when determining which elements to automatically load since the relevant ones might change.

Also, do not lazy-load elements that are right next to the viewport edge to avoid issues that might surface during scrolling. In fact, if you have five or fewer media elements on your page, it might not be worth the time and effort to implement lazy loading. In those cases, any savings in load time might be offset by the coding effort.

Lazy loading With Cloudinary

Cloudinary is a cloud-based service that simplifies and automates the process of manipulating, optimizing, and delivering images and videos, optimized for all devices at all bandwidths. With Cloudinary’s SDKs, which you can seamlessly integrate with your app, you can efficiently transform, optimize, and deliver media, largely through automation. Now that lazy loading works in all modern browsers, it’d be a smart move to lazy-load resources with the Cloudinary SDK’s image tag.

Give it a try by signing up for Cloudinary. We offer generous free plans to get you started.

Want to Learn More About Lazy Loading?

Getting Killer Page Performance With Angular Lazy Loading

As one of the most popular frameworks for building web apps, Angular can significantly speed up development and make many useful features accessible, including lazy loading.

The article How to Get Killer Page Performance With Angular Lazy Loading defines lazy loading and explains why it’s important, how to implement it in Angular and with ngx-loadable, and how to lazy-load with Cloudinary.

Lazy-Loading JavaScript for High-Speed Webpage Performance

JS, long the default language for building websites and web apps, is universally supported and relatively easy to master due to its many built-in capabilities. Among those capabilities is support for lazy loading.

The article Lazy-Loading JavaScript for High-Speed Webpage Performance explains why developers like to use JS libraries, what lazy loading is, how JS supports lazy loading, how to simplify implementation with Intersection Observer, and how to lazy-load with Cloudinary.

Lazy-Loading React and Boosting Page Performance for Your Apps

A popular JS library often used for creating user interfaces, React enables you to build reusable components that are rendered for websites and web apps. Among those components are tools for applying lazy loading and delivering the best possible experience for users.

The article Lazy-Load React and Boost Page Performance for Your Apps describes React components, including the ones that support lazy loading, and the procedures for putting them into practice and for boosting page performance with Cloudinary.

Lazy Loading for Optimal Performance

The article Lazy Loading for Optimal Performance tells you why lazy loading is useful, how it works, when to apply it, and how to get started.

Progressive Web Apps: Architecture and Examples

Progressive web apps (PWAs) are lightweight, native-like apps that offer better user experiences and that enable advanced interactivity. You can, for example, enable offline access for users through PWAs without having to create a standalone app.

The article Progressive Web Apps: Architecture and Examples defines PWAs and chronicles their architecture, the elements they need, and user expectations. Also explored are best practices for developing PWAs and ways in which to optimize PWAs’ visual content through Cloudinary.

Guides on Performance Testing

We have authored in-depth guides on three topics that relate to performance testing.

Image Optimization

Images and videos take up most of the page-load time on most websites. To make your website load faster and improve user experience and engagement, be sure to reduce the file size of images without hurting quality.

See these top articles in our Image Optimization Guide:

Image Formats

Advancements in image- and video-compression techniques have resulted in new formats like WebP and JPEG 2000, which deliver superior quality with a smaller file size. This guide describes traditional image and video formats, the benefits of the modern ones, and how to take advantage of them in your websites and web applications.

See these top articles in our Image Formats Guide:

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