Created
November 6, 2010 09:17
-
-
Save thsutton/665306 to your computer and use it in GitHub Desktop.
Get the value of an HTTP response header in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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