Member-only story
Lazy Loading in Angular — A Beginner’s Guide
Improve your website’s user experience and SEO
Lazy loading is the process of loading components, modules, or other assets of a website as required. Since Angular creates an SPA (single-page application), all of its components are loaded at once. Secondly, a lot of unnecessary libraries or modules might be loaded as well.
For a small application, that would be OK. But as the application grows, the load time will increase if everything is loaded at once. Lazy loading allows Angular to load components and modules as and when needed.
In order to understand how lazy loading works we first need to understand the building block of Angular: NgModules.
What Are NgModules?
Angular libraries like RouterModule, BrowserModule, and FormsModule are NgModules. Angular Material, which is a third-party library, is also a type of NgModule. An NgModule consists of files and code related to a specific domain or having a similar set of functionalities.
A typical NgModule file declares components, directives, pipes, and services. It can also import other modules that are needed in the current module.
One of the important advantages of NgModules is they can be lazy-loaded. Let’s have a look at how we can configure lazy loading.
How To Create NgModules
In this tutorial, we will create two modules (Module A and Module B) that will be lazy-loaded. On the main screen, we will have two buttons for loading each module lazily.
Create the project
Create a new Angular project called lazy-load-demo by executing the command below:
ng new lazy-load-demo --routing --style css
code lazy-load-demo
Here, we are creating a new project with routing. Secondly, we mention the stylesheet format to CSS. The second command opens your project in VS Code.
Root module
By default, a root module or app module is created under /src/app
. Below is the NgModule file that’s created: