How to check if an image exists on the server in JavaScript

In modern JavaScript, you can use the Fetch API to check if an image or any other resource file exists on the server.

Fetch is a simple promise-based API for asynchronously fetching resources from the server.

Here is an example that uses Fetch API to check if an image exists:

fetch('/img/bulb.svg', { method: 'HEAD' })
  .then(res => {
    if (res.ok) {
      console.log('Image exists.')
    } else {
      console.log('Image does not exist.')
    }
  })
  .catch(err => console.log('Error:', err))

The above example code sends an HTTP HEAD request and checks the response code. If the response is OK (status code 200), it prints that the image is found. Otherwise, it doesn't exist.

Make sure that you are making the same-origin requests or that CORS are enabled on the server when using the Fetch API. Otherwise, it will throw an error that cross-origin resource sharing (CORS) is blocked. Also, Fetch API is only supported by modern browsers and doesn't work in Internet Explorer.

For more browser support, you can always use the good old XHR that works in Internet Explorer 6 and higher:

// create an XHR object
const xhr = new XMLHttpRequest()

// listen for `onload` event
xhr.onload = () => {
  if (xhr.status == 200) {
    console.log('Image exists.')
  } else {
    console.log('Image does not exist.')
  }
}

// create a `HEAD` request
xhr.open('HEAD', '/img/bulb.svg')

// send request
xhr.send()

The above examples are not just limited to checking the presence of images on the server. They can be used to check for the existence of any other file like JavaScript, Cascading Style Sheets (CSS), PDF, etc.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.