From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../web/api/htmlimageelement/decode/index.html | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 files/zh-cn/web/api/htmlimageelement/decode/index.html (limited to 'files/zh-cn/web/api/htmlimageelement/decode') diff --git a/files/zh-cn/web/api/htmlimageelement/decode/index.html b/files/zh-cn/web/api/htmlimageelement/decode/index.html new file mode 100644 index 0000000000..b04b67a431 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/decode/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLImageElement.decode() +slug: Web/API/HTMLImageElement/decode +translation_of: Web/API/HTMLImageElement/decode +--- +
+

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 接口的 decode() 方法返回一个当图片解码后可安全用于附加到 DOM 上时 resolves 的 {{jsxref("Promise")}} 对象。 这可用于在将图片附加到一个 DOM 中的元素(或作为一个新元素加入 DOM 中)之前启动加载,所以在将图像添加到 DOM 时可以立即渲染图像。这反过来,防止了将图像加入DOM后图像的加载造成下一帧渲染的延迟。

+
+ +

语法

+ +
var promise = HTMLImageElement.decode();
+ +

参数

+ +

无.

+ +

返回

+ +

一个一旦数据准备好可供使用时resolve的promise对象.

+ +

异常

+ +

{{domxref('DOMException')}} 表示解码图像时出错。

+ +

使用提示

+ +

一个 decode() 的潜在用例:当在加载一个非常大的图片时(例如,一个在线相册),你可以在加载初期提供一个低分辨率的缩略图,之后通过实例化一个 {{domxref("HTMLImageElement")}} 将该图像替换为一个全分辨率图像,设置其 source 为全分辨率图像URL,使用 decode() 获取一旦全分辨率图像准备好被使用时 resolved 的 promise 对象。这时你可以使用当前可用的全分辨率图像替换之前的低分辨率图像。

+ +

例子

+ +

以下例子展示了如何使用 decode() 方法来控制一个图像插入 DOM 的时机。若不使用 {{domxref('Promise')}} 返回方法,你将在图像的 {{event("load")}} 事件处理函数中将图像加入 DOM 中,通过 {{event("error")}} 事件处理函数处理错误。

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

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#dom-img-decode','decode()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLImageElement.decode")}}

-- cgit v1.2.3-54-g00ecf