0

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?

DigitalM0nkey
  • 127
  • 1
  • 3
  • 8

1 Answers1

0

Use onerror on the image element.

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}`;
};

const createRandomImage = function () {
  const img = document.createElement('img')
  img.src = randomImage()
  img.onerror = function () {
    img.src = randomImage()
  }
  return img
}

document.body.appendChild(createRandomImage())
document.body.appendChild(createRandomImage())
document.body.appendChild(createRandomImage())
document.body.appendChild(createRandomImage())
dotnetCarpenter
  • 10,019
  • 6
  • 32
  • 54
  • This look like it will fix my problem. Thank you. – DigitalM0nkey Dec 05 '19 at 01:13
  • With my current setup we are attempting to use this function on the server-side. However, 'document' is not defined. Is there are way to make this work server-side? – DigitalM0nkey Dec 05 '19 at 04:13
  • @DigitalM0nkey in short, *no*. My solution is taking advantage of the `onerror` property of the Document Object Model (DOM) Image Element. Unless you are using [jsdom](https://github.com/jsdom/jsdom), which might be overkill, you do not have access in a server-side environment to the DOM. What is your setup? – dotnetCarpenter Dec 05 '19 at 18:33