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

Image-Editing Basics and a Tutorial for Automation With AI

You likely find yourself continually editing images for enhancement by eliminating flaws and tweaking the overall presentation, typically with software tools. Examples of basic editing are straightening, cleaning, and cropping images, as well as adjusting the contrast, exposure, and white balance. With advanced software like Cloudinary, you can automate not only editing tasks, such as quality adjustment and encoding, but also delivery.

Read more
Tips for Retaining Audience Through Engaging Videos

Measuring the level of interest your videos generate helps you produce compelling content. The measurement and optimization approach must, however, address the various aspects of each video, including the A/B test hypothesis and iterations. A high engagement rate spells effective videos; a low engagement rate calls for content improvement.

Read more
Forbes Cloud 100: When the Stars Align

In 2017, when Cloudinary first made the Forbes Cloud 100 as a ‘Rising Star,’ it was an incredibly proud moment for the company. In 2018 we graduated from Rising Star status to be acknowledged as part of the incredible Cloud 100, the top 100 SaaS companies in the world. Today marks our third consecutive year on this prestigious list.

Read more
A Cloudinary-Enhanced Student-ID App

I’m an instructional designer on Cloudinary’s Solutions and Training team. As the COVID-19 pandemic emerged in March, like other global organizations, we pivoted to set up virtual courses. As much as we looked forward to resuming in-person classes in the future, we switched gear to focus on the virtual way of learning.

Read more
Image Formats: Getting it Right

Image formats, which are standards for digital images, can be uncompressed, compressed, raster based, or vector based. You determine the DNA of your images with the formats you adopt, each of which offering different capabilities. For example, rasters generate images with pixels; vectors, with vectors or proportional formulas. PNGs can display logos without background; JPEGs always come with backgrounds. This article explains the main properties of the various image formats, including their basic concepts and pros and cons.

Read more