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.
Code
// 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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.