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 page loads of 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.

Recent Blog Posts

Enhance Your Travel Site With Cloudinary in Anticipation of a Return to New Normal

Read more
The Benefits of Headless DAMs

Headless is not a buzzword anymore. In fact, the concept of headless architecture is gaining momentum due to the flexibility it offers for composing new experiences and for tackling the undue complexity of an ever-evolving technology stack. That’s because while the evolution of the martech landscape has enabled disruptive, digital innovations, the approach of buying point solutions for solving specific challenges can expose companies to the complicated nature of new technologies, systems, and platforms.

Read more

Building Display Ads With Transparent Video

By Afzaal Ahmad Zeeshan
Build Web Ads With Transparent Video to Attract User Engagement

Billions of views on the Internet every day drive one of the biggest industries on the planet: advertising. The sheer size of that market and the competitive nature of vying for consumer attention results in a constant need for innovation. Readers are jaded, and display ads are blind spots.

Read more
How Cloudinary's Media Optimizer Helps E-Businesses Deliver Superior Web Performance

As a technology company, Cloudinary owes its success to its ability to build solutions that address the most critical challenges you, our customers, face. The companies we serve run the gamut of digital businesses—retailers and direct-to-consumer brands, media and entertainment, travel and hospitality—which, coincidentally, all care about the same things.

Read more