I have a function that loads a random image. However, sometimes the image does not exist which is a bit of a problem.
This is an example of a valid and invalid link:
Valid https://picsum.photos/id/96/500/300
Invalid https://picsum.photos/id/97/500/300
Here is the code:
const randomImage = function() {
const defaultWidth = 500;
const defaultHeight = 300;
const randomNumber = Math.ceil(Math.random() * 1048);
console.log(
"Random Image",
`https://picsum.photos/id/${randomNumber}/${defaultWidth}/${defaultHeight}`
);
return `https://picsum.photos/id/${randomNumber}/${defaultWidth}/${defaultHeight}`;
};
Is there a way to check if the url is a valid image before adding it to the function?