image error Swaps In A Fallback Source
Listen for the image error event and swap in a fallback source exactly once, so a broken avatar never survives a failed request.
Code
// A broken image URL fires error on the element — swap in a fallback
// source instead of leaving a broken icon in the feed
const img = document.querySelector('.avatar');
img.addEventListener('error', () => {
// The dataset guard makes the replacement run exactly once, so a
// failing fallback can never loop forever
if (img.dataset.fallbackApplied) return;
img.dataset.fallbackApplied = 'true';
img.src = '/static/avatar-fallback.png';
img.alt = 'default avatar';
});
img.addEventListener('load', () => {
console.log(`avatar loaded: ${img.naturalWidth}x${img.naturalHeight}`);
});
// error and load are mutually exclusive per attempt: after the swap,
// only the fallback's own outcome reaches these listenersThe one-shot swap on error
The listener on img reacts to the error event by checking img.dataset.fallbackApplied first: when the flag is set it returns immediately, otherwise it sets the flag and replaces the source with img.src = '/static/avatar-fallback.png' plus a new alt. That dataset guard is what makes the replacement run exactly once — if the fallback URL itself failed, the second error event finds the flag and bails out instead of looping forever.
Where this code runs
It touches document.querySelector and element properties that exist only in a browser, so it belongs in a page (or the DevTools console), not under plain Node. error and load are mutually exclusive per attempt: after the swap, the file’s load listener reports the fallback’s own outcome with `avatar loaded: ${img.naturalWidth}x${img.naturalHeight}` — the intrinsic size of whatever image finally arrived.
The line that guards the retry
if (img.dataset.fallbackApplied) return;
img.dataset.fallbackApplied = 'true';
img.src = '/static/avatar-fallback.png';
Setting the flag before changing src closes the loop window: by the time the fallback’s result event arrives, the guard is already in place.
Interactive Tools for This Topic
FAQ
- Does image error Swaps In A Fallback Source 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.