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 |
浏览器兼容性
加载中…