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.