HTMLImageElement: decoding 屬性
HTMLImageElement 介面的 decoding 屬性為瀏覽器提供了一個關於如何解碼影像的提示。更具體地說,是應該等待影像解碼後再呈現其他內容更新,還是不等待。
值
表示解碼提示的字串。可能的值有:
用法說明
decoding 屬性為瀏覽器提供了一個提示,說明它應該將影像解碼與其他任務一起執行("sync"),還是允許在完成之前渲染其他內容("async")。實際上,這兩個值之間的差異通常難以察覺,而且在有差異的情況下,通常有更好的方法。
對於插入到視口內的 DOM 中的影像,"async" 可能導致未樣式化的內容閃爍,而 "sync" 可能導致少量的卡頓。使用 HTMLImageElement.decode() 方法通常是實現原子性呈現而又不延遲其他內容的好方法。
對於插入到視口外的 DOM 中的影像,現代瀏覽器通常會在它們滾動到檢視之前對其進行解碼,使用這兩種值不會有明顯的區別。
示例
在下面的示例中,在影像下載過程中,頁面上很可能顯示一個空白影像。設定 decoding 屬性不會阻止這種情況。
js
const img = new Image();
img.decoding = "sync";
img.src = "img/logo.png";
document.body.appendChild(img);
下載後插入影像可以使 decoding 屬性更具相關性。
js
async function loadImage(url, elem) {
return new Promise((resolve, reject) => {
elem.onload = () => resolve(elem);
elem.onerror = reject;
elem.src = url;
});
}
const img = new Image();
await loadImage("img/logo.png", img);
// Using `sync` can ensure other content is only updated with the image
img.decoding = "sync";
document.body.appendChild(img);
const p = document.createElement("p");
p.textContent = "Image is fully loaded!";
document.body.appendChild(p);
然而,一個更好的解決方案是使用 HTMLImageElement.decode() 方法來解決這個問題。它提供了一種非同步解碼影像的方法,延遲將其插入 DOM,直到它完全下載並解碼,從而避免了上述空白影像的問題。如果你正在動態地將一個現有影像替換為新影像,這一點尤其有用,而且它還可以防止在影像解碼時,與此程式碼無關的繪製操作被延遲。
使用 img.decoding = "async" 可能會避免在解碼時間較長時延遲其他內容的顯示。
js
const img = new Image();
img.decoding = "async";
img.src = "img/logo.png";
document.body.appendChild(img);
規範
| 規範 |
|---|
| HTML # dom-img-decoding |
瀏覽器相容性
載入中…
另見
HTMLImageElement.decode()方法<img>元素decoding屬性- What does the image decoding attribute actually do? (tunetheweb.com, 2023)