HTMLImageElement: decode() 方法
HTMLImageElement 接口的 decode() 方法返回一个 Promise,该 Promise 在图像解码完成并且可以安全地将其附加到 DOM 后解析。
这可用于在将图像附加到 DOM 元素(或将其作为新元素添加到 DOM)之前启动图像加载,以便图像在添加到 DOM 后可以立即渲染。这反过来又可以防止在将图像添加到 DOM 后的下一帧渲染导致图像加载时的延迟。
语法
js
decode()
参数
无。
返回值
一个 Promise,一旦图像数据准备好使用,它将以 undefined fulfilled。
异常
EncodingError-
一个
DOMException,指示在解码图像时发生错误。
用法说明
decode() 的一个潜在用例:加载非常大的图像时(例如,在在线相册中),您可以先显示一个低分辨率的缩略图,然后通过实例化一个新的 HTMLImageElement 来替换该图像,将其源设置为高分辨率图像的 URL,然后使用 decode() 获取一个 Promise,该 Promise 在高分辨率图像准备好使用后解析。届时,您就可以用现在可用的高分辨率图像替换低分辨率图像。
示例
基本用法
以下示例显示了如何使用 decode() 方法来控制何时将图像附加到 DOM。
js
const img = new Image();
img.src = "nebula.jpg";
img
.decode()
.then(() => {
document.body.appendChild(img);
})
.catch((encodingError) => {
// Do something with the error.
});
避免空白图像
在下面的示例中,在图像下载过程中,您很可能会在页面上看到一个空白图像。
js
const img = new Image();
img.src = "img/logo.png";
document.body.appendChild(img);
使用 decode() 将会延迟将图像插入 DOM,直到图像完全下载和解码,从而避免了空白图像问题。
js
async function getImage() {
const img = new Image();
img.src = "img/logo.png";
await img.decode();
document.body.appendChild(img);
const p = document.createElement("p");
p.textContent = "Image is fully loaded!";
document.body.appendChild(p);
}
如果您动态地用新图像替换现有图像,这一点尤其有用,并且还可以防止此代码以外的不相关绘制在图像解码期间被延迟。
规范
| 规范 |
|---|
| HTML # dom-img-decode-dev |
浏览器兼容性
加载中…
另见
- What does the image decoding attribute actually do? (tunetheweb.com, 2023)
HTMLImageElement.decoding属性