Image Decode Await Before Reveal

img.decode() resolves once pixels are ready to paint, so awaiting it before insertion removes the half-decoded flash of a plain src swap.

JavascriptResilience

Code

javascriptsnippet
26 lines
// img.decode() resolves only once the pixels are fully ready to paint —
// await it before insertion so no half-decoded frame ever flashes
const slot = document.querySelector('#preview-slot');

async function reveal(url) {
  const next = new Image();
  next.src = url;
  next.alt = 'product preview';

  await next.decode();
  slot.replaceChildren(next);
  next.classList.add('revealed');
  console.log('revealed size:', next.naturalWidth + 'x' + next.naturalHeight);
  return next;
}

reveal('/img/hero.avif').catch((err) => {
  // decode() rejects on broken sources — no load/error event wiring needed
  console.log('decode rejected:', err.constructor.name);
});

// decode() also works on images that are already in the document
const inline = document.querySelector('img.chart');
if (inline) {
  inline.decode().then(() => console.log('chart ready to paint'));
}

How it works

Everything happens inside the function reveal.

The async parts await their results, which keeps ordering predictable.

What to watch for

  • The whole dependency story is the language version itself.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

The entry-point signature is async function reveal(url)

The demo output is labeled (revealed size:, decode rejected:, chart ready to paint); each label names the call that printed it.

Core lines

reveal('/img/hero.avif').catch((err) => {
  // decode() rejects on broken sources — no load/error event wiring needed
  console.log('decode rejected:', err.constructor.name);
});
await next.decode();

Interactive Tools for This Topic

FAQ

Does Image Decode Await Before Reveal run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.