WebP 是什麼?

網頁使用的圖片主流格式有JPG、PNG、GIF、SVG…等等,受限於圖片品質與大小的關係,為了保持圖片品質與大小,圖片檔能壓縮的幅度有限,因此Google於2010年公布了WebP的這項圖片格式。

WebP是一種圖片檔案格式,結合了失真與無失真壓縮技術減小圖片檔案大小、更迅速地在網路上傳輸的技術,這讓圖片在保持高品質的同時,不再需要像JPG或PNG那麼大的檔案空間。簡單來說,就是讓圖片在網路上跑得更快,同時不失去好看的效果。

The difference in size between the same image in JPG and WebP formats.
The difference in size between the same image in JPG and WebP formats.
  1. 檔案小:根據維基百科的資料顯示,WebP的檔案大小比PNG檔少了45%,即使PNG檔已經使用壓縮工具進行壓縮處理過,WebP仍可以減少28%的檔案大小。
  2. 可動態與透明化:可以擁有PNG的透明背景圖片效果以及GIF的動態圖片效果
  3. 支援度: 2024/1/19的Can I Use顯示已經有 96.41%的支援度,但是在較舊版的ios Safari 13.7還是沒有支援

如何在使用 WebP 格式的同時,又能確保兼容性?

1.使用 <img> element時 : < picture > 和 < source >

推薦指數:⭐⭐⭐⭐⭐
原因:html WebP fallback最佳利器

picture element支援度:Can I Use)

Can I Use:<picture>
Can I Use:<picture>

透過<picture>元素,您可以在<source>中使用 WebP 格式的圖片。如果瀏覽器不支援,則會回退至最後的 <img>作為替代方案。

<picture>的介紹可以看這篇

範例如下:

<picture>
<source srcset="https://www.gstatic.com/webp/gallery/1.sm.webp" type="image/webp">
<img src="https://www.gstatic.com/webp/gallery/1.jpg">
</picture>
example:<picture>
example:<picture>

2.使用background-image時 : @supports

推薦指數:⭐⭐⭐⭐⭐
原因:@supports 的普及,它不僅在圖片瀏覽器支援度判斷方面更為廣泛,甚至在其他判斷情境中也得到了廣泛應用

@supports支援度:Can I Use)

Can I Use:@supports
Can I Use:@supports

@supports 判斷瀏覽器是否支援,若支援則使用新的 WebP 圖片設定,若不支援則回退至原本的圖片

範例如下:

<!-- html -->
<div class="backgroundImage supports"></div>
<!-- css -->
/* Using the CSS nesting syntax */
.backgroundImage {
width: 320px;
height: 214px;
display: block;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
background-image: url("https://www.gstatic.com/webp/gallery/1.jpg");
&.supports {
@supports (
background-image: url("https://www.gstatic.com/webp/gallery/1.sm.webp")
) {
background-image: url("https://www.gstatic.com/webp/gallery/1.sm.webp");
}
}
}
}
example:@supports
example:@supports

3.使用background-image時 : image-set()type()

推薦指數:⭐⭐⭐
原因:較少看到image-set用法,且支援度較低

image-set()支援度:Can I Use)

Can I Use:image-set
Can I Use:image-set

使用 image-set 可以根據瀏覽器是否支援 WebP 圖片,若支援則呈現 WebP,否則呈現設定的另一瀏覽器支援的格式。然而,考慮到瀏覽器可能不支援 image-set,建議在原始的圖片背景設定中補充一個作為fallback的選項

<!-- html -->
<div class="backgroundImage supports"></div>
<!-- css -->
/* Using the CSS nesting syntax */
.backgroundImage {
width: 320px;
height: 214px;
display: block;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
background-image: url("https://www.gstatic.com/webp/gallery/1.jpg");
&.imageSet {
background-image: image-set(
url("https://www.gstatic.com/webp/gallery/1.sm.webp") type("image/webp"),
url("https://www.gstatic.com/webp/gallery/1.jpg") type("image/jpeg")
);
}
}
example:image-set
example:image-set

codepen範例

結語

總結來說,雖然WebP的支援度相對較高,但如果你的目標使用者中有使用舊版瀏覽器的人群,可能需要對WebP做一些備援處理。這可以透過不同的方式來實現,包括在使用 <img> 元素時使用 <picture> 和 <source> 元素,使用 @supports 規則處理背景圖片,以及在使用背景圖片時運用 image-set() 和 type()。

--

--