NgOptimizedImage
簡介
Angular 的 NgOptimizedImage 指令可以自動處理圖片優化問題,提升應用程式的效能和 Core Web Vitals 分數。
基本設置
1. 導入指令
import { NgOptimizedImage } from '@angular/common';
@Component({
standalone: true,
imports: [NgOptimizedImage],
// ...其他配置
})
2. 基本使用方式
@Component({
template: `
<!-- 靜態圖片 -->
<img
ngSrc="/assets/logo.svg"
alt="Angular logo"
width="32"
height="32"
/>
<!-- 動態圖片 -->
<img
[ngSrc]="logoUrl"
[alt]="logoAlt"
width="32"
height="32"
/>
`
})
關鍵特性
1. 強制寬高設置
為防止版面偏移(Layout Shift),必須設置圖片的寬度和高度:
<img
ngSrc="/path/to/image.jpg"
width="800" // 等於 800px
height="600"
alt="描述"
/>
2. Fill 模式
當需要圖片填充容器時,可使用 fill 屬性。
注意: 使用 fill 模式時,父元素必須設置以下其中一種定位樣式:
position: "relative"
position: "fixed"
position: "absolute"
否則圖片將無法正確渲染。
使用範例:
<!-- 父容器必須設置 position: relative|fixed|absolute -->
<div class="image-container">
<img
ngSrc="image.png"
fill
alt="背景圖片"
/>
</div>
<style>
.image-container {
position: relative;
width: 100%;
height: 300px;
}
</style>
3. 優先載入
對於重要圖片(如 LCP 元素),加入 priority 屬性:
<img
ngSrc="hero-image.jpg"
priority
width="1200"
height="600"
alt="首圖"
/>
進階功能:圖片加載器
1. 設置基本加載器
import { provideImgixLoader } from '@angular/common';
// 在 providers 中配置
@Component({
providers: [
provideImgixLoader('https://your-domain.imgix.net/')
]
})
2. 使用加載器
<!-- 最終 URL: https://your-domain.imgix.net/image.jpg -->
<img
ngSrc="image.jpg"
width="800"
height="600"
alt="使用加載器的圖片"
/>
最佳實踐
LCP(Largest Contentful Paint)優化:
為主要視覺區域的大圖加上 priority 屬性
確保這些圖片優先載入
防止版面偏移:
永遠設置 width 和 height 屬性
或使用 fill 模式並正確設置容器樣式
響應式圖片:
<img ngSrc="image.jpg" width="800" height="600" sizes="(max-width: 768px) 100vw, 800px" alt="響應式圖片" />
Last updated