DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Best Javascript Frameworks for 2022
  • Feature Modules in Angular – Why Required and When to Use?
  • Building a Full-Stack Resume Screening Application With AI
  • Mastering React Efficiency: Refactoring Constructors for Peak Performance

Trending

  • How To Replicate Oracle Data to BigQuery With Google Cloud Datastream
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • AI-Assisted Coding for iOS Development: How Tools like CursorAI Are Redefining the Developer Workflow
  1. DZone
  2. Coding
  3. JavaScript
  4. Lazy Loading in Web Applications: JS, Angular, and React

Lazy Loading in Web Applications: JS, Angular, and React

For whichever flavor of JS you end up using.

By 
Gilad Maayan user avatar
Gilad Maayan
·
Mar. 22, 21 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
12.5K Views

Join the DZone community and get the full member experience.

Join For Free

Lazy loading is a common technique to improve performance in web applications. The concept is simple—instead of loading everything upfront, leading to the annoying “loading” message experienced by many users of single page applications—the application loads components only when they are actually requested or needed by the user. 

Lazy loading is supported natively in many web development frameworks. In this article, I discuss the concept of lazy loading and how to implement it in pure JavaScript, and using built-in functionality in Angular and React. Finally, I provide a quick tutorial showing a real life implementation of lazy loading in a single page application.

What is Lazy Loading?

Lazy loading (also known as dynamic function loading) allows developers to specify program components that should not be loaded by default when the program starts. Normally, the system loader automatically loads the initial program and all dependencies. When using lazy loading, dependencies are only executed when explicitly needed. 

If users don’t initially use some of the dependent components, lazy loading can significantly improve performance. The downside of lazy loading is that function calls to lazy loading components require extra guidance and time. So before embarking on a lazy loading journey, consider how much of a performance improvement it can provide.

The concept of lazy loading has been widely used in web development frameworks. Most commonly, it is used to delay loading of rich media—images, video, and dynamic elements—that are below the fold and initially not visible to website users. For long, complex web pages or interface screens, lazy loading images and video can dramatically improve page load time, which can boost user engagement, conversion, and search ranking.

Lazy loading works differently in different frameworks:

  • In pure JavaScript, there are simple scripts that can help you load images when they enter the user’s viewport, using the Intersection Observer API supported by most major browsers.

  • In Angular, there are several libraries that can help you lazily load NgModules, and you can also configure lazy loading natively using Routes. 

  • In React, you can use the built-in React.lazy() method to delay loading of components, or wrap multiple components for lazy loading using the Suspense component.

Lazy Loading with Javascript

There are many JavaScript lazy loading libraries. Because lazy loading is a sensitive operation that impacts the user experience, select a well tested lazy load library that delivers a consistent experience across all popular browsers. Below are a few robust, well known libraries.

lazysizes

Lazysizes library is a self-initializing lazy loader for responsive images, iframes, widgets, and more. The script identifies images that are critical to view, and prioritizes them in the loading cycle to improve performance, without hurting the user experience.

Yall.js

Yall uses Intersection Observer and event listeners to identify when an element enters the user’s viewport. The library supports all major HTML elements, and can be used in all modern browsers (including Internet Explorer 11). However, it doesn't support lazy loading of background images.

jQuery Lazy

Lazy is a lightweight JQuery plugin for lazy loading of content. You can use it with jQuery or Zepto (a popular minimalistic jQuery-compatible API). Lazy provides native support for images and backgrounds. It can perform lazy loading of non-image content through plugins and custom loaders.

Tuupola Lazyload

Tuupola Lazyload focuses on simplicity and ease of use. Its minified script is only 956 bytes, significantly smaller than most other options. It only uses Intersection Observer to decide when to load images, while other libraries use a combination of several methods to lazy load different types of objects on different triggers. This means it is less flexible, but also has better browser compatibility, due to the wide support for Intersection Observer.

Lazy Loading in Angular

In Angular, NgModules are eagerly loaded by default. This means that NgModules load immediately when users access the application, regardless of whether they are truly needed or not. However, Angular does support lazy loading for NgModules. 

To implement lazy loading in Angular, you need to create a feature module using the `--route` flag. You can then configure a route to lazy-load the module, as shown in the following example:

Java
 




x
11


 
1
const routes: Routes = [
2

          
3
  {
4

          
5
    path: 'customers',
6

          
7
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
8

          
9
  }
10

          
11
];



You can learn more about this process in the Angular documentation, as well as other techniques for configuring lazy loading in the application user interface (UI).

In addition, you can use packages. Here are two Angular component packages you can use for lazy loading:

  • ngx-loadable—an open source package that provides lightweight components for Angular. Each package contains a simple application programming interface (API), which supports loading indicators. Once you load the package, you can use it for any number of page loads.

  • hero-loader—an open source package that can help you lazy-load Angular modules in response to certain triggers, such as mouseover, route change, and click. The hero-loader package is provided as an extension of a built-in feature of `loadChildren`.

Lazy Loading Components in React

React achieves lazy loading with two primary components: the React.lazy() method and Suspense.

React.lazy()

The React.lazy() method makes it easy to split your React application at the component level, via dynamic imports.

In a typical React application, there are many components and third-party libraries, all of which are loaded when the user loads the first page. This means a large block of JavaScript will be downloaded and executed by users when they enter the first page, resulting in slow load times and a poor user experience. 

React.lazy() provides built-in methods to break down the components of a React application into separate JavaScript blocks. You can load components when actually needed by users or dependent components. 

Suspense

Suspend works together with React.lazy()—it is a component needed to wrap lazily-loaded components. It can combine several components and lazy load them together when required. Suspense has a fallback property, which specifies which React components should be shown to the user while the lazy components are loading.

Quick Tutorial: Lazy Loading in React with React.lazy and Suspense

There are many techniques you can use to lady load in React. Below is a quick rundown explaining how to use React.lazy and Suspense, based on the in-depth tutorial by Abhimanyu Chauhan. You can find the source code in this github repository.  

Prerequisites:

  • React version 16.6.0 or higher 

  • Export the module:

Java
 




xxxxxxxxxx
1


 
1
export default Login;
2

          
3
export const abc = className; **Not Valid **



1. Import the component by using React.lazy

const Login = React.lazy(() => import(‘./Components/Login’)); 


2. Display fallback content by using Suspense

Import the Suspense module from React:

import React,{Suspense} from ‘react’; 

Next, wrap the Login component by using the Suspense component. Here, the message “Loading…” is displayed while the content is loading:

<Suspense fallback={<div>Loading…</div>}><Login /></Suspense> 


3. Test to make sure lazy loading is working

Implement the process above on a live page. You can then use Chrome DevTools to see if the lazy loading process you set up is working:

  • Search for 0.chunk.js—this bundle is initially loaded without dynamic import. 

  • Search for 1.chunk.js—is called when React.lazy imports a component. 

Conclusion

In this article I covered lazy loading concepts, and how to achieve lazy loading in three popular web development environments:

  • You can achieve lazy loading in pure JavaScript applications using libraries like lazysizes or Yall.js

  • You can achieve lazy loading in Angular by using the --route flag, and configuring a route to lazy load a module

  • You can achieve lazy loading in React using the React.lazy() and the Suspense component

I hope this will be helpful in improving the performance of your applications and delivering content users actually need, just in time.

Lazy loading application React (JavaScript library) AngularJS

Opinions expressed by DZone contributors are their own.

Related

  • The Best Javascript Frameworks for 2022
  • Feature Modules in Angular – Why Required and When to Use?
  • Building a Full-Stack Resume Screening Application With AI
  • Mastering React Efficiency: Refactoring Constructors for Peak Performance

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.