img.decode Reveals Paint-Ready Images

Await img.decode() before revealing an image so the DOM swap happens only when the bitmap is paint-ready, with a fallback when decoding fails.

TypescriptResilience

Code

typescriptsnippet
15 lines
// 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';
    });
}

Inside the code

The snippet is organized around the function showPreview.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Entry signature: function showPreview(url: string, slot: HTMLElement)

Key statements

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

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `showPreview` at load time.