如何在 Angular 中进行性能优化?
在 Angular 中进行性能优化是提高应用响应速度、减少资源消耗的重要手段。以下是一些常见的性能优化策略,涵盖从模板编写、变更检测到懒加载等多个方面:
🌟 核心优化策略
1. 使用 OnPush 变更检测策略
默认的 Default 策略会遍历整个组件树,影响性能。
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
适用于:
- 数据是不可变的(如通过
@Input()接收的新对象) - 使用
async pipe绑定 Observable
2. 懒加载模块(Lazy Loading)
将大模块拆分成按需加载模块,减少初始加载体积。
const routes: Routes = [
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];
3. 懒加载组件(Component Level Lazy Loading)
Angular 14+ 支持独立组件懒加载:
import { Component, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-dashboard',
template: `
<button (click)="loadChart()">加载图表组件</button>
<ng-container #container></ng-container>
`
})
export class DashboardComponent {
constructor(private viewContainerRef: ViewContainerRef) {}
async loadChart() {
// lazy load component
const { ChartComponent } = await import('../lazy/chart/chart.component');
this.viewContainerRef.clear();
this.viewContainerRef.createComponent(ChartComponent);
}
}
4. 使用 trackBy 优化 *ngFor
避免不必要的 DOM 重建:
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
trackById(index: number, item: Item) {
return item.id;
}
5. 避免在模板中执行函数
模板中执行函数会在每次变更检测中重复调用:
❌ 不推荐:
<div>{{ calculateTotal() }}</div>
✅ 推荐:把结果缓存为变量
⚡ 性能增强技巧
6. 使用 async pipe 自动订阅/取消订阅
避免手动订阅造成内存泄漏。
<div *ngIf="data$ | async as data">{{ data.name }}</div>
7. 减少 DOM 元素和绑定
简洁模板、避免不必要的数据绑定。
8. Web Workers
对于 CPU 密集型任务,如大数据处理,可使用 Web Worker:
const worker = new Worker(new URL('./app.worker', import.meta.url));
9. 避免大型第三方库或按需引入
比如:
- 使用 lodash-es + tree shaking
- Angular Material:使用
MatButtonModule而非整个MaterialModule
📦 构建相关优化
10. 使用 AOT 编译(默认开启)
Ahead-of-Time 编译生成更小、更快的应用。
11. 开启生产模式
在 main.ts 中添加:
import { enableProdMode } from '@angular/core';
enableProdMode();
12. Tree Shaking + Minification
Angular CLI 默认支持,确保使用 ng build --prod
13. 使用 Service Worker 实现 PWA 缓存
ng add @angular/pwa