Lazy Loading & Preloading Strategies
Optimize Angular bundle size with lazy loading.
Lazy Loadingโ
Feature modules are loaded on demand:
const routes: Routes = [
{
path: "tasks",
loadChildren: () =>
import("./tasks/tasks.module").then((m) => m.TasksModule),
},
{
path: "employees",
loadChildren: () =>
import("./employees/employees.module").then((m) => m.EmployeesModule),
},
];
Preloading Strategiesโ
PreloadAllModulesโ
Preloads all lazy modules after the app loads:
@NgModule({
imports: [
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})
]
})
Custom Preloadingโ
Preload only modules the user is likely to visit:
@Injectable()
export class SelectivePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
return route.data?.["preload"] ? load() : of(null);
}
}
Bundle Analysisโ
# Analyze bundle sizes
yarn build --stats-json
npx webpack-bundle-analyzer dist/stats.json
Tipsโ
- Keep feature modules independent
- Use
SharedModulefor common components - Avoid importing large libraries in
CoreModule - Use dynamic imports for heavy components
Related Pagesโ
- Angular Module Architecture โ module structure
- Frontend Performance โ optimization