65

Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?

My motivation is to conserve bandwidth.

If not, is it possible to fake it?

1
  • Yes, check this... Commented Dec 2, 2008 at 11:13

3 Answers 3

107

Easy, just use the HEAD method, instead of GET or POST:

function UrlExists(url, callback) { var http = new XMLHttpRequest(); http.open('HEAD', url); http.onreadystatechange = function() { if (this.readyState == this.DONE) { callback(this.status != 404); } }; http.send(); } 

This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload, onerror and ontimeout rather than onreadystatechange).

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, sometimes the abstraction of a framework hides the underlying functionality!
Any idea how cross-browser this is? The jQuery documentation states "Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers." api.jquery.com/jQuery.ajax
@doekman: Synchronous requests will block all JS-dependent tasks (Douglas Crockford once wrote that "Synchronous programming is disrespectful and should not be employed in applications which are used by people."). Think of all the people that unknowingly copied the example without thinking. For that reason, the answer has served poorly for years. The update both shows how to use asynchronous requests and makes explicit the fact that the example shouldn't be copied verbatim.
I applaud the fact that this answer is jQuery free. Even the simplest of JS questions on SO is almost always answered with a jQ solution.
Any chance that b.c. this is just a HEAD request, one can go cross-domain?
|
5

The more modern approach is to use the Fetch API which replaced XMLHttpRequest.

e.g. (within an async function)

const url = "https://example.com"; const response = await fetch(url, { method: "HEAD" }); console.log(`Got status: ${response.status}`); 

Comments

-5

An XMLHTTPRequest object should have

getAllResponseHeaders(); getResponseHeader("header-name") 

defined on it

1 Comment

Downvote: The answer seems to confuse the HTTP HEAD method with HTTP headers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.