Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created November 6, 2010 09:17
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save thsutton/665306 to your computer and use it in GitHub Desktop.
Save thsutton/665306 to your computer and use it in GitHub Desktop.
Get the value of an HTTP response header in JavaScript
/**
* Read the value of a header in the current document.
*
* This uses a [single] XMLHTTPRequest to do a HEAD of the current document
* and fetch HTTP response header values. Note that the implementation is
* rather stupid in that it spins waiting for the XMLHTTPRequest to complete
* if it hasn't been called yet.
*
* @param name string
* The name of the header.
* @return string
* The value (or undefined).
*/
var readHeader = (function() {
// Hidden cache for the headers...
var _request = undefined;
return function(name) {
//
// We have a request cached...
///
if (_request) {
return _request.getResponseHeader(name);
}
//
// We need to get the request...
//
else {
// Do the request and wait for it to complete.
_request = new XMLHttpRequest();
_request.open("HEAD", window.location, true);
_request.send(null)
while (_request.readyState != 4) {};
return _request.getResponseHeader(name);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment