Lazy Loading with Angular
In Angular, lazy loading is a technique that allows you to load JavaScript components and modules asynchronously when a specific route is activated. Lazy loading can help shrink the initial download and enhance performance, especially if you have a large solution with many components with complex routing.
Some of the benefits of lazy loading include:
- Minimize the size of the initial load bundle.
- Load feature areas only when requested by the user.
- Speed up load time for users that only visit certain areas of the application.
Start by creating a new module within your existing application. Determine where you want this module to live within your current structure. For the Sample App, we’re using /src/app/modules. Once navigating to that location in a command prompt, use CLI to create a new module.
Next create a new components folder within the lazy-load module folder, navigate to it and create a new component using CLI.
In your newly created module, import the necessary modules to create a basic page. Then set up a simple route using the ** wildcard so when loading this module it defaults to the root path.
Once your new module is set up, update the route table in your parent application to include a route definition to the lazy load module.
Instead of specifying a component property, use the loadChildren
property and import the module, supplying the path relative to the app root.
Finally, create a navigation item pointing to your new module route.
To confirm it’s working, load your application in a browser. When you navigate to the new /LazyLoad
url, you will see a new js file loaded in the Network tab of your Inspector window.
