SVGImageElement: decoding 屬性
SVGImageElement 介面的 decoding 屬性為瀏覽器提供了一個提示,說明是應該同步解碼影像還是非同步解碼影像。
值
一個代表解碼提示的字串。可能的值有:
用法說明
decoding 屬性為瀏覽器提供了一個提示,說明是應該與其他任務一起在單個步驟中("sync")執行影像解碼,還是允許在影像解碼完成之前渲染其他內容("async")。實際上,這兩種值之間的差異通常難以察覺,而且在存在差異的情況下,往往有更好的解決方案。
對於插入到視口內的 DOM 中的影像,"async" 可能導致未樣式化內容的閃爍,而 "sync" 可能導致輕微的卡頓。使用 SVGImageElement.decode() 方法通常是實現原子化呈現而不會阻礙其他內容的一種更好方式。
對於插入到視口外的 DOM 中的影像,現代瀏覽器通常會在它們滾動到檢視之前對其進行解碼,無論使用哪種值都不會有明顯的區別。
示例
在下面的示例中,您可能會在頁面上看到一個空白影像,因為它正在下載。設定 decoding 屬性不會阻止這種情況。
js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
img.decoding = "sync";
img.setAttribute("href", "img/logo.svg");
svg.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 SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
await loadImage("img/logo.svg", img);
// Using `sync` can ensure other content is only updated with the image
img.decoding = "sync";
svg.appendChild(img);
const text = document.createElementNS(SVG_NS, "text");
text.textContent = "Image is fully loaded!";
svg.appendChild(text);
然而,一個更好的解決方案是使用 SVGImageElement.decode() 方法來解決這個問題。它提供了一種非同步解碼影像的方式,延遲將其插入 DOM 直到完全下載和解碼,從而避免了上述空白影像問題。如果您正在動態地將現有影像替換為新影像,這一點尤其有用,並且還可以防止在此程式碼之外的其他無關繪製在影像解碼時被掛起。
使用 img.decoding = "async" 可以在解碼時間較長時避免阻止其他內容顯示。
js
const SVG_NS = "http://www.w3.org/2000/svg";
const svg = document.querySelector("svg");
const img = document.createElementNS(SVG_NS, "image");
img.decoding = "async";
img.setAttribute("href", "img/logo.svg");
svg.appendChild(img);
規範
| 規範 |
|---|
| HTML # dom-img-decoding |
瀏覽器相容性
載入中…