HTMLImageElement.decode() - Web APIs 编辑

The decode() method of the HTMLImageElement interface returns a Promise that resolves when the image is decoded and it is safe to append the image to the DOM. This can be used to initiate loading of the image prior to attaching it to an element in the DOM (or adding it to the DOM as a new element), so that the image can be rendered immediately upon being added to the DOM. This, in turn, prevents the rendering of the next frame after adding the image to the DOM from causing a delay while the image loads.

Syntax

var promise = HTMLImageElement.decode();

Parameters

None.

Return value

A Promise which is resolved once the image data is ready to be used.

Exceptions

EncodingError
A DOMException indicating that an error occurred while decoding the image.

Usage notes

One potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new HTMLImageElement, setting its source to the full-resolution image's URL, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. At that time, you can then replace the low-resolution image with the full-resolution one that's now available.

Examples

The following example shows how to use the decode() method to control when an image is appended to the DOM. Without a Promise-returning method, you would add the image to the DOM in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler.

const img = new Image();
img.src = 'nebula.jpg';
img.decode()
.then(() => {
  document.body.appendChild(img);
})
.catch((encodingError) => {
  // Do something with the error.
})

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'decode()' in that specification.
Living StandardInitial definition.

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:134 次

字数:4157

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文