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

published: 30 May 2022

2 min read

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, the image doesn't exist.

Make sure that you are either making the same-origin requests or CORS is 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 browsers 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.

How to check if an image exists on the server in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, file