← 中文资源

简体中文版本

img.decode 确认解码完成再显示

img.decode 等位图完全解码后再替换进 DOM,避免空帧与半解码闪烁;源无效或损坏时 promise 以 EncodingError 拒绝,页面改走兜底文案而不显示破图。

阅读英文原文

实现说明

活动部件是函数 showPreview。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 文件在加载时定义 showPreview。

主签名形如 function showPreview(url: string, slot: HTMLElement)

核心语句

.catch(() => {
  // rejects on invalid or broken sources (e.g. EncodingError)
  slot.textContent = 'preview unavailable';
});

代码示例

// img.decode() resolves once the bitmap is fully decoded and ready to paint,
// so swapping it into the DOM cannot flash an empty or half-drawn frame.
function showPreview(url: string, slot: HTMLElement): void {
  const img = new Image();
  img.src = url;
  img.alt = 'chart for the selected range';

  img
    .decode()
    .then(() => slot.replaceWith(img))
    .catch(() => {
      // rejects on invalid or broken sources (e.g. EncodingError)
      slot.textContent = 'preview unavailable';
    });
}