Skip to content

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.

What is lazy loading? Simply put, it’s a technique that delays loading certain parts of a webpage, such as images and other resources, until they are needed. This approach isn’t limited to web development but is a common strategy in programming, contributing significantly to efficiency and resource management.

This is part of an extensive series of guides about Front-End Development.

This article covers the following topics:

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.

A simple yet effective way to implement lazy loading is by using the HTML loading attribute in image tags. For example: <img src=”image.png” loading=”lazy” alt=”…” width=”200″ height=”200″>. This method is supported in most modern browsers and allows images to load only when they are about to enter the viewport, contributing to quicker page load times.

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.

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.

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

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:

import React, { Suspense } from 'react';

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

function MyComponent() {
 return (
  <div>
   <Suspense fallback={<div>Loading...</div>}>
    <OtherComponent />
   </Suspense>
  </div>
 );
}
Code language: JavaScript (javascript)

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

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

It’s also worth noting that the Intersection Observer API in JavaScript offers a powerful way to implement lazy loading. This API allows for asynchronous monitoring of how page elements intersect with each other or with the user’s viewport, acting as a trigger for content loading. This approach is particularly useful for dynamic and responsive websites where content visibility changes based on user interaction and screen size.

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, 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, 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.

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:

const routes: Routes = [
 {
  path: 'customers',
  loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
 }
];
Code language: JavaScript (javascript)

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.

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

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.

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.

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.

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.

**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.

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

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:

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:

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of front-end development.

Authored by Cloudinary

Authored by Cloudinary

Authored by Cloudinary

Back to top