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.
Code
// 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.
documentexist 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
Base64 Image PreviewPreview a Base64 or data URI image, detect its MIME type from the magic bytes, and see the decoded byte size without uploading anything.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.