Lazy loading is a commonly used technique. However, in Angular it seems that the granularity level of this technique stops at the module level.
That means that you can have module main that loads in the browser, and then on special occasion module B and C and D can be loaded lazily.
Almost all tutorials on web explain that. However, is there a way to load components lazily?
Consider this simple example that user goes inside the application, and when clicks "invoices" link, URL changes to the new route /invoice/list
and a progress bar shows loading, while the invoices
component including HTML and JS is being loaded inside the browser, is registered dynamically with the main module, and is being shown in the relevant outlet. Is that possible with Angular?
As the application grows, its performance on the browser reduces significantly and lowers user experience. In this tutorial, I'll walk you through the concepts of lazy loading in Angular and how it can improve the application loading time on the browser.
Lazy loading is the technique used in optimizing your web and mobile apps, this works by rendering only needed or critical user interface items first, then quietly rendering the non-critical items later. As we build code components the application grows, and the bundle gets very cumbersome in size.
To lazy load the component, we will use the import() method inside an async/await function. The above function first clears the container; otherwise, on every click of the button, the new instance of GreetComponent would be added in the container.
To lazy load Angular modules, use loadChildren (instead of component ) in your AppRoutingModule routes configuration as follows. content_copy const routes: Routes = [ { path: 'items', loadChildren: () => import('./items/items. module'). then(m => m.
Lazy loading a component is not possible. Reason for this behavior is the structure of angular. Components in angular have to be part of a module. Angular module is a container where you define all the components, services, pipes e.t.c. present inside. While building the application dist, all the dependencies declared in the module are included to make a chunk (transpiled js code). All the directly imported modules together form the main chunk whereas modules marked as lazily loaded form a separate chunk that sits on the server untill the respective route is hit and a call for it is made from the client. Now components do not form a chunk and hence it is not possible
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With