Lazy Loading in Web Applications: JS, Angular, and React
For whichever flavor of JS you end up using.
Join the DZone community and get the full member experience.
Join For FreeLazy 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:
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
}
];
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:
xxxxxxxxxx
export default Login;
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 whenReact.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 moduleYou 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.
Opinions expressed by DZone contributors are their own.
Comments