Lazy loading in Angular is a technique that allows you to load components on demand rather than loading all of them at the start.
This can significantly improve the performance of your application, especially as it grows in size.
Eager Strategy
Our current router configuration now uses an Eager Loading strategy.
It means that all source code is available inside the main.js file, that will be loaded by index.html when the application starts.
We can easily verify it in two ways:
1. Build report
Create a build of the application using npm run build.
The report clearly shows that we only have one main.js file:
Now imagine an application with dozens of pages, hundreds of components and a lot of business logic.
This approach does not scale!
We can easily generates a main.js file whose size easily reaches megabytes in few time.
Applying a lazy loading strategy to the router we can split the main.js file in several files (aka chunks) that will be loaded only when a specific route is loaded.
2. Running the application
Run the application in your browser, open the Network console of Dev Tools and you'll see that only a main.ts file is loaded when the application starts, while nothing is loaded when a new page is visited:
Run in a Web Server
You should always open a web application in a web server for security issues.
When we run "npm run start" the application already starts a built-in web server.
But when we create a build, we should run the compiled version of our project in a web server.
For a quick check we can use, for instance, the http-server package.
Open terminal, go to the project root folder and run this command to open a new webserver:
terminal
It will generate a new URL that we can open in the browser and we can easily check the result of the build.