关于 angular-performance
面向 Angular 开发的性能优化技能,整理图像加载、延迟加载、路由和渲染策略,供构建或优化应用时参考。
主要功能
- 01使用 NgOptimizedImage 优化图像
- 02通过 @defer 延迟加载组件
- 03配置惰性路由
- 04选择 SSR、CSR 或 SSG
- 05优化计算并避免生命周期重排
适用场景
- 01为关键图像设置加载属性
- 02推迟加载视口外内容
- 03按页面需求选择渲染方式
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ gentleman-programming/ gentleman-skills --skill angular-performance安装后在 Claude Code 中输入/angular-performance确认已加载。
详细介绍
NgOptimizedImage(图片必需)
import { NgOptimizedImage } from '@angular/common';
@Component({
imports: [NgOptimizedImage],
template: `
<img ngSrc="hero.jpg" width="800" height="400" priority>
<img ngSrc="thumb.jpg" width="200" height="200">
<img ngSrc="bg.jpg" fill>
<img ngSrc="photo.jpg" width="400" height="300" placeholder>
`
})
规则
- 始终设置
width和height(或fill) - 为 LCP(最大内容绘制)图片添加
priority - 使用
ngSrc,而不是src fill图片的父级必须设置position: relative/fixed/absolute
@defer - 延迟加载组件
@defer (on viewport) {
<heavy-component />
} @placeholder {
<p>Placeholder shown immediately</p>
} @loading (minimum 200ms) {
<spinner />
} @error {
<p>Failed to load</p>
}
触发条件
| 触发条件 | 使用时机 |
|---|---|
on viewport | 首屏以下的内容 |
on interaction | 点击/聚焦/悬停时加载 |
on idle | 浏览器空闲时加载 |
on timer(500ms) | 延迟后加载 |
when condition | 表达式为 true 时加载 |
@defer (on viewport; on interaction) {
<comments />
}
@defer (when showComments()) {
<comments />
}
延迟加载路由
// Single component
{
path: 'admin',
loadComponent: () => import('./features/admin/admin').then(c => c.AdminComponent)
}
// Feature with child routes
{
path: 'users',
loadChildren: () => import('./features/users/routes').then(m => m.USERS_ROUTES)
}
SSR 与 Hydration
bootstrapApplication(AppComponent, {
providers: [
provideClientHydration()
]
});
| 场景 | 使用方式 |
|---|---|
| SEO 至关重要(博客、电商) | SSR |
| Dashboard/管理后台 | CSR |
| 静态营销网站 | SSG/Prerender |
耗时计算
| 方案 | 适用时机 |
|---|---|
| 优化算法 | 始终优先选择 |
| 纯管道 | 缓存单个结果 |
| 记忆化 | 缓存多个结果 |
computed() | 派生信号状态 |
绝不要在生命周期钩子(ngOnInit、ngAfterViewInit)中触发布局重排/重绘。
资源
评论
支持 Markdown