Categories
JavaScript Answers

How to verify image URL with JavaScript?

Spread the love

Sometimes, we want to verify image URL with JavaScript.

In this article, we’ll look at how to verify image URL with JavaScript.

How to verify image URL with JavaScript?

To verify image URL with JavaScript, we can try to load the URL into an Image object.

For instance, we write

const doesImageExist = (url) =>
  new Promise((resolve) => {
    const img = new Image();

    img.src = url;
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
  });

to define the doesImageExist function that returns a promise.

We define a promise with the Promise constructor called with a function that creates an Image object.

We set the src property to url to load the url into the img element.

And then we listen for success or error by setting the onload and onerror properties to functions respectively.

When onload is called, the url is a valid image URL so we call resolve with true.

If onerror is called, the url isn’t a valid image URL so we call resolve with false.

Conclusion

To verify image URL with JavaScript, we can try to load the URL into an Image object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *