Lazily loading routes
So far all of our routes are eagerly loaded, which means that as soon as the application loads, so do all the routes, whether or not they are immediately necessary.
For large applications with lots of routes, consider lazy loading, a design pattern that loads routes (Components) as needed.
Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
To lazy load Angular modules, we will use loadComponent
in routes configuration.
loadComponent
expects a function that uses the dynamic import syntax to import your lazy-loaded module only when it’s needed.- The dynamic import is promise-based and gives you access to the component, where the component’s class can be called.
export const routes: Routes = [
{path: '', redirectTo: 'sports', pathMatch: 'full'},
{path: 'sports', loadComponent: () => import('./forms/sports/sports.component').then(m => m.SportsComponent)},
{path: 'grocery', loadComponent: () => import('./forms/grocery/grocery.component').then(m => m.GroceryComponent)}
];