I am making a news website with news API for practice and sometimes some images do not load. So how can I set a logical condition like "use this image if this does not load".
Thanks
You can do that like this...
Replace the invalid_link and https://placeimg.com/200/300/animals with your links.
<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">
It's not clear how you're handling the images - are they hardcoded in the HTML, are they in an array?
This example uses a Promise-based method to replace all bad images with dummy images.
An array of image objects (name, src), is mapped over. For each iteration (for each object) it calls checkIfImageExists with the src, and based on what the function returns (either true or false) returns either the original object (true) or a new object with the dummy image as the src.
When you run the snippet you will see that badImage (2nd object) has had the src replaced with the dummy image URI.
function checkIfImageExists(src) {
return new Promise(res => {
const img = new Image();
img.src = src;
if (img.complete) {
res(true);
} else {
img.onload = () => {
res(true);
};
img.onerror = () => {
res(false);
};
}
});
}
const dummy = 'https://dummyimage.com/48x48/633a63/000000.png&text=n/a';
const imgs = [
{ name: 'flower', src: 'https://images.unsplash.com/photo-1649922694096-35448dfd411f' },
{ name: 'badImage', src: 'https://images.unsplash.com/photo-1649922694096-35448dfd411eeeddddd' },
{ name: 'sign', src: 'https://images.unsplash.com/photo-1649928210166-52c1b1d8279e' }
];
function filterImages(data) {
return data.map(async obj => {
const exists = await checkIfImageExists(obj.src);
if (exists) return obj;
return { ...obj, src: dummy };
});
}
async function main() {
console.log('Waiting for the image-checking to complete...');
const filtered = await Promise.all(filterImages(imgs));
console.log(filtered);
}
main();