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.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.