Technical Info
>
Framework Considerations: Angular
>
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.
Create new module
C:[path to application root]/src/app/modules>ng g m lazy-load
CREATE src/app/modules/lazy-load/lazy-load.module.ts (192 bytes)
Next create a new components folder within the lazy-load module folder, navigate to it and create a new component using CLI.
Create new component
C:[path to application root]/src/app/modules/lazy-load/components>ng g c lazy-load
CREATE src/app/modules/lazy-load/component/lazy-load.component.ts (117 bytes)
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.
Finally, create a navigation item pointing to your new module route.
Navigation item for new module
<jha-nav-buttonjhaIconType="Information"jhaText="Lazy Load Example"jhaTooltip="Example of a lazy loaded module"jhaRouterLink="/LazyLoad"></jha-nav-button>
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.
The modules-lazy-load-lazy-load-module.js file is independent of the main bundle and waits to load until the page is requested in the browser.
Support options
Have questions on this topic?
Join the
Responsive UI team in Microsoft Teams to connect with the community.