Testing for the Existence of Remote Files

Originally published on my old QuintusQuill Console blog in October 2008.

There are plenty of cases where you might want to check whether a remote file (a text document or an image) exists. We can do this using a HEAD XMLHttpRequest.

Set up your XMLHttpRequest like normal:

var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4) {
if (request.status == 200) {
[Code to Execute if File Exists...]
}
else {
[Code to Execute if File Doesn't Exist...]
}
}
}

When you open it, however, replace "GET" with "HEAD" (url is the URL of your file):

request.open("HEAD", url, true);

Finally, send it like normal:

request.send("");

This is very good way to quickly determine if an image exists—it's much faster than creating a new Image object, assigning it a src, then setting up onload and onerror handlers.

Obviously, if you were to use this multiple times, it would be best to put the code into a function.

Subscribe to my newsletter

Get new articles delivered to your inbox.