提供最佳化的裝飾圖片

網頁功能: image-set()

透過 CSS 提供最佳化的裝飾圖片,可提升感知效能,同時不影響視覺品質。使用 image-set() CSS 函式,即可為瀏覽器提供單一背景或遮罩圖片的多個選項。您可以指定新式格式 (例如 AVIF 或 WebP) 和不同解析度 (例如 1x 和 2x)。瀏覽器會動態選取相容的最小圖片,為使用者裝置提供適當的像素密度。

注意:如果圖片可能是 Largest Contentful Paint (LCP) 元素 (例如大型主頁橫幅),請注意,瀏覽器的預先載入掃描器無法偵測到 CSS 中透過 image-set() 參照的圖片。這可能會大幅延遲圖片載入,並對 LCP 造成負面影響。如果是 LCP 候選項目,建議改用標準 HTML <img> 或 <picture> 標記,或使用 <link rel=preload> 選項和 media 屬性預先載入圖片。

導入作業

只要 CSS 需要 <image> 值,就可以使用 image-set() 函式,最常見於 background-image、content 或 mask-image。請注意,雖然同時提供圖片格式 (透過 type()) 和解析度 (例如 1x 或 2x) 可獲得最佳結果,但這兩個引數都是選用。

.gallery-item {
  /* Provide multiple resolutions and formats using image-set() */
  /* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG). 
     The browser will stop at the first supported format. */
  background-image: image-set(
    url("gallery.avif") type("image/avif") 1x,
    url("gallery-2x.avif") type("image/avif") 2x,
    url("gallery.webp") type("image/webp") 1x,
    url("gallery-2x.webp") type("image/webp") 2x,
    url("gallery.jpg") type("image/jpeg") 1x,
    url("gallery-2x.jpg") type("image/jpeg") 2x
  );
  
  /* Standard decorative properties */
  background-size: cover;
  background-position: center;
}

備用策略

如果舊版瀏覽器不支援 image-set() 函式,您「必須」在 image-set() 規則「之前」提供標準圖片宣告。這項漸進增強策略仰賴 CSS 的階層特性:系統會忽略不支援的規則。

.gallery-item {
  /* MANDATORY: Fallback for browsers that do not support image-set() */
  background-image: url("gallery.jpg");
  
  /* Modern browsers will apply this and override the fallback */
  background-image: image-set(
    url("gallery.avif") type("image/avif") 1x,
    url("gallery-2x.avif") type("image/avif") 2x,
    url("gallery.jpg") type("image/jpeg") 1x,
    url("gallery-2x.jpg") type("image/jpeg") 2x
  );
}