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.
If you are going to need to test for files often, I’d recommend that you put the code into a function:
function testFile(url)
{
// Setup options
var options = arguments[1];
if (!options) { options = {}; }
// Create the request
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4) {
if (request.status == 200) {
// File Exists
if (options.onSuccess) { options.onSuccess(); }
}
else {
// File Doesn't Exist
if (options.onFailure) { options.onFailure(); }
}
}
}
request.open("HEAD", url, true);
request.send("");
}
Then you can call it like this:
testFile("http://quintusquill.com/anImage.jpg", {
onSuccess: function() {
alert("File Exists!");
},
onFailure: function() {
alert("File Doesn't Exist!");
}
});
Since we’ve set up the function to use “options” (see here for more on options), you don’t have to provide either the onSuccess or onFailure callbacks (however, you won’t get any answer if you don’t specify at least one of them).
