To dynamically change the src attribute of an <img> tag in JavaScript, validate that the target element is an HTMLImageElement (and that the URL string is non-empty and safe for your scheme policy), assign imgElement.src = nextUrl (or imgElement.setAttribute("src", nextUrl) when working with raw attribute strings), and attach load / error listeners inside a try / catch block so broken URLs, network failures, or stale images are handled cleanly without uncaught errors.
1. Updating img.src Safely with Validation and load / error Handling
Validate the HTMLImageElement and target URL string, attach one-time load and error handlers before assigning imgElement.src, and guard against missing or invalid inputs:
// Dynamically update an <img> element's src attribute with load/error handling
function setImageSourceSafely(imgElement, nextSrc, {
fallbackSrc = null,
allowDataUri = false,
onLoad = null,
onError = null
} = {}) {
if (!(imgElement instanceof HTMLImageElement)) {
throw new TypeError("Expected imgElement to be an HTMLImageElement.");
}
if (typeof nextSrc !== "string" || nextSrc.trim().length === 0) {
throw new TypeError("Expected nextSrc to be a non-empty string.");
}
if (fallbackSrc !== null && (typeof fallbackSrc !== "string" || fallbackSrc.trim().length === 0)) {
throw new TypeError("Expected fallbackSrc to be null or a non-empty string.");
}
if (typeof allowDataUri !== "boolean") {
throw new TypeError("Expected allowDataUri to be a boolean.");
}
const trimmedSrc = nextSrc.trim();
const lowerSrc = trimmedSrc.toLowerCase();
if (lowerSrc.startsWith("javascript:")) {
throw new Error("Refusing javascript: URI in image src.");
}
if (!allowDataUri && lowerSrc.startsWith("data:")) {
throw new Error("Data URIs are disabled for image src.");
}
try {
const handleLoad = () => {
cleanup();
if (typeof onLoad === "function") {
onLoad(imgElement, trimmedSrc);
}
};
const handleError = (event) => {
cleanup();
if (typeof onError === "function") {
onError(imgElement, trimmedSrc, event);
}
if (fallbackSrc && imgElement.src !== fallbackSrc) {
imgElement.src = fallbackSrc.trim();
}
};
const cleanup = () => {
imgElement.removeEventListener("load", handleLoad);
imgElement.removeEventListener("error", handleError);
};
imgElement.addEventListener("load", handleLoad, { once: true });
imgElement.addEventListener("error", handleError, { once: true });
imgElement.src = trimmedSrc;
return true;
} catch (error) {
throw new Error(`Failed updating image src: ${error.message}`);
}
}
// Example usage:
// try {
// const avatarImg = document.querySelector("#user-avatar");
// setImageSourceSafely(avatarImg, "/assets/avatars/user-42.webp", {
// fallbackSrc: "/assets/avatars/default-avatar.png",
// onLoad: (el) => el.classList.remove("is-loading")
// });
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Assigning
imgElement.src = urlimmediately starts fetching the new image: Attachloadanderrorlisteners before setting.srcto avoid missing fast/cached events. - Avoid
img.completealone as proof of a valid image:img.completecan betrueeven after a failed load (naturalWidth === 0).
2. Preloading or Swapping Multiple Image Sources with a Map
When cycling thumbnails, themes, or product variants, store verified URLs in a Map (keyed by variant ID or state name) and optionally preload before swapping to avoid blank flashes:
// Swap an <img> src using a validated Map of image keys -> URLs
function applyImageVariantFromMap(imgElement, variantMap, variantKey) {
if (!(imgElement instanceof HTMLImageElement)) {
throw new TypeError("Expected imgElement to be an HTMLImageElement.");
}
if (!(variantMap instanceof Map)) {
throw new TypeError("Expected variantMap to be a Map instance.");
}
if (typeof variantKey !== "string" || variantKey.trim().length === 0) {
throw new TypeError("Expected variantKey to be a non-empty string.");
}
try {
if (!variantMap.has(variantKey)) {
throw new RangeError(`No image URL found in variantMap for key "${variantKey}".`);
}
const targetUrl = variantMap.get(variantKey);
if (typeof targetUrl !== "string" || targetUrl.trim().length === 0) {
throw new TypeError(`Invalid image URL for variant "${variantKey}".`);
}
imgElement.src = targetUrl.trim();
return targetUrl.trim();
} catch (error) {
throw new Error(`Failed applying image variant "${variantKey}": ${error.message}`);
}
}
// Example usage:
// const themeAssets = new Map([
// ["light", "/images/logo-light.svg"],
// ["dark", "/images/logo-dark.svg"]
// ]);
// const logoEl = document.querySelector("#brand-logo");
// applyImageVariantFromMap(logoEl, themeAssets, "dark");
- Keep
alttext synchronized when changing image meaning: If a dynamic image changes its subject rather than just its resolution/theme, updateimgElement.altas well for accessibility. - Use
Maprather than plain objects for dynamic variant keys: Prevents accidental lookup collisions withObject.prototypeproperties.
3. srcset, Caching, and DOM Pitfalls
Keep these practical browser details in mind when updating <img> elements dynamically:
imgElement.srcreturns a resolved URL, whereasimgElement.getAttribute("src")returns the raw attribute string: Relative paths like"/img/pic.png"resolve to"https://example.com/img/pic.png"when read via.src.- Responsive
srcset/<picture>sources can override or accompanysrc: If an<img>hassrcsetor sits inside a<picture>element, updatesrcset/<source>elements as needed so the browser selects the intended image candidate. - Guard against
nullfromdocument.querySelector(...): Passingnullinto a function expecting anHTMLImageElementshould fail fast with a clearTypeErrorrather than throwing a confusing property-access error later.
