Hugo Cox Hugo Cox - 3 years ago 236
HTTP Question

Retrieve response headers from including external javascript file

I am looking for a way to include an external .js file and receive the response headers from that request.

<script src="external/file.js?onload=callback">
function callback(data) {

Obviously, this doesn't seem to work.

How do I get the response header from including the javascript?
It can not be a second request.

In your answer, please avoid using jQuery.

Thanks for an help.

Answer Source

getAllResponseHeaders(): The XMLHttpRequest.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string, or null if no response has been received. If a network error happened, an empty string is returned.

That means you need to load the external js with a XMLHttpRequest:

Moreover, in this way you load only one time the file.

function loadScript(url) {
    var oXmlHttp = new XMLHttpRequest();
    oXmlHttp.onreadystatechange = function () {
        if (oXmlHttp.status == 200 || oXmlHttp.status == XMLHttpRequest.DONE) {

            var x = oXmlHttp.getAllResponseHeaders();

            if (oXmlHttp.responseText != null) {
                var oHead = document.getElementsByTagName('HEAD').item(0);
                var oScript = document.createElement("script");
                oScript.language = "javascript";
                oScript.type = "text/javascript";
                oScript.defer = true;
                oScript.text = oXmlHttp.responseText;
    }'get', url);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download