Angular Lazy load学习笔记

Angular Lazy load学习笔记
最新回答
只是偶尔想起你

2026-07-30 23:54:53

Angular Lazy Load 学习笔记

懒加载(Lazy Loading),也称为代码分割(Code Splitting),是一种将JavaScript代码拆分为多个chunk的技术。通过懒加载,当用户首次访问应用时,无需加载整个应用所需的所有JavaScript代码,而是仅加载当前页面所需的代码块,从而提升应用性能和加载速度。

懒加载的核心概念

  • 代码分割:将TypeScript编译后的JavaScript代码拆分为多个chunk。
  • 按需加载:仅加载当前页面渲染所需的代码块,而非整个应用。
  • 性能优化:减少初始加载时间,提升用户体验。

在Angular项目中,执行ng build命令后,可以查看打包生成的chunk名称和大小。默认情况下,所有组件会被打包到一个main chunk中。

默认打包行为

默认情况下,Angular应用中的所有组件会被打包到main chunk中。例如,开发一个MyCartComponent,其会被打包到main chunk中,对应的JavaScript代码如下:

实现懒加载的步骤

要让Angular应用的组件支持懒加载,需将其与main chunk分开打包。以下是具体实现步骤:

1. 配置路由使用loadChildren

在AppRoutingModule中,配置路由时使用loadChildren属性动态加载模块,而非直接使用component属性。

import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' }];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: []})export class AppRoutingModule { }2. 创建功能模块

为每个懒加载的路由创建对应的功能模块(Feature Module),例如CustomersModule:

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { CustomersRoutingModule } from './customers-routing.module';import { CustomersComponent } from './customers.component';@NgModule({ imports: [ CommonModule, CustomersRoutingModule ], declarations: [CustomersComponent]})export class CustomersModule { }3. 配置功能模块的路由

在功能模块中配置子路由,例如CustomersRoutingModule:

import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { CustomersComponent } from './customers.component';const routes: Routes = [ { path: '', component: CustomersComponent }];@NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule]})export class CustomersRoutingModule { }4. 验证打包结果

执行ng build命令后,检查打包结果。此时,main chunk、customers chunk和orders chunk会分别打包,表明懒加载已生效。

懒加载的运行时表现

在浏览器中访问应用时,初始页面不会加载customers或orders的代码块。只有当用户点击对应链接时,才会动态加载相应的chunk。

  • 初始加载:未访问customers或orders页面时,仅加载main chunk。

  • 点击链接后:访问customers页面时,动态加载customers chunk。

懒加载的优势

  • 减少初始加载时间:用户无需等待所有代码下载完成即可开始使用应用。
  • 优化资源利用:按需加载代码块,减少不必要的网络请求和内存占用。
  • 提升用户体验:应用响应更快,尤其在大型应用中效果显著。

总结

通过配置路由使用loadChildren属性,并将功能模块与路由分离,可以实现Angular组件的懒加载。懒加载是优化Angular应用性能的重要技术,尤其适用于大型应用。通过代码分割和按需加载,可以显著提升应用的加载速度和用户体验。