Grimoire-
Command
.es

GNU+Linux command memo

JavaScript : detect broken images

Détecter les images dont le chargement a échoué.

1st method: testing for .naturalWidth property of an image HTML node.

if (img.naturalWidth === 0)
	throw `${src} -> naturalWidth === 0`

2nd method: testing for .decode() execution.

try {
	await img.decode()
} catch (exc) {
	throw `${src} -> can't .decode()`
}

Testing all images:

const imgs = document.querySelectorAll('img')
let src
for (const i of imgs) {
	src = i.attributes.src.value
	if (!src || !i.attributes.alt.value)
		throw `missing required attribute src= or alt= for <img id="${i.id}" class="${i.classList}"`
	if (i.naturalWidth === 0)
		throw `${src} -> naturalWidth === 0`
	try {
		await i.decode()
	} catch (exc) {
		throw `${src} -> can't .decode()`
	}
}