Obtain headers from receiving an external JavaScript file

I am trying to find a way to import an external .js file and access the response headers from that request.

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

Unfortunately, this method does not seem to be effective.

Is there a way to retrieve the response header when importing the javascript without making a second request?

Please refrain from using jQuery in your solution.

Thank you for any assistance.

SOLUTION Credit to gaetanoM

oXmlHttp.withCredentials = true; is used for CORS

oXmlHttp.responseType = 'text'; is for DOM input?

Below is the current code I am working with;

<script>
    function loadScript(url) {

    var oXmlHttp = new XMLHttpRequest();            
        oXmlHttp.withCredentials = true;
        oXmlHttp.responseType = 'text';
        oXmlHttp.open('GET', url, true);
        oXmlHttp.onload = function () {

          if( oXmlHttp.status >= 200 || oXmlHttp.status == XMLHttpRequest.DONE ) {

            var x = oXmlHttp.getAllResponseHeaders();
            console.log(x);

            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;
                    oHead.appendChild(oScript);

            }

          }

        }
        oXmlHttp.send();
    }

    loadScript("http://url/to/file.js");        
</script>

Answer №1

Exploring the XMLHttpRequest.getAllResponseHeaders() Method: This method retrieves all response headers, separated by CRLF (carriage return line feed), in string format. It returns null if no response is received or an empty string in case of a network error.

For loading external JavaScript files efficiently, you can utilize a single XMLHttpRequest:

By employing this approach, you only request and load the file once, enhancing performance.

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


                var headers = xhttp.getAllResponseHeaders();
                console.log(headers);


                if (xhttp.responseText != null) {
                    var head = document.getElementsByTagName('HEAD').item(0);
                    var script = document.createElement("script");
                    script.language = "javascript";
                    script.type = "text/javascript";
                    script.text = xhttp.responseText;
                    head.appendChild(script);
                }
            } else {
                console.log("Error", xhttp.statusText)
            }
        }
    }
    xhttp.open('get', url);
    xhttp.send();
}


loadScript("11.js?onload=callback");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

Tips on customizing the appearance of the dropdown calendar for the ngx-daterangepicker-material package

Is there a way to customize the top, left, and width styling of the calendar? I'm struggling to find the right approach. I've been working with this date range picker. Despite trying to add classes and styles, I can't seem to update the app ...

Error: The function pathRegexp is not defined

While attempting to conduct tests on my project with jest, I encountered an error code that seems unrelated to the actual testing process. It appears to be more of a dependency or Node Express compatibility issue. `● Test suite failed to run TypeError: ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Styling CSS for disabled nested elements

In a project I am currently working on, I've noticed that disabled items do not appear disabled enough. My initial plan was to easily address this issue with some CSS. Typically, adjusting the opacity is my go-to solution to achieve the desired effec ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Javascript - understanding variable scope

Hey there! I have some code that I need help with var idx = 0; var size = 0; do { response.push({ key: "data" + idx, ajaxOptions: function () { var data = this.getPref("groupsCN"); var items = data.split('; ...

Changing the Material UI imported Icon on click - a step-by-step guide

Hey there, I'm currently working with React JS and Redux. I have a challenge where I need to change the star outline icon to a filled star icon on click. The icon is located just after emailRow in the emailRow__options section. Can someone assist me w ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

Using JQuery, retain only the initial N elements in a list and discard the rest

I'm looking to streamline a list of items in the DOM by keeping only the first N items, ideally through the use of slice and remove methods. Could someone provide me with the JQuery syntax for removing items that come after the first N in the list? ...

Troubleshooting tips for optimizing Opera and Internet Explorer performance

I'm currently on the hunt for solutions or techniques to debug my jquery script specifically under the Opera/IE browser. It appears that the ajax $.post() request is either not being sent at all, or it's being sent to the wrong address, among oth ...

In what way does React ensure state encapsulation while passing state as a prop to a child component?

This question pertains to an intricate aspect of React, specifically focusing on state encapsulation. The example provided in this response to the query mentioned in this post illustrates how React props that are objects are passed by reference: const ...

I prefer to keep PHP fatal errors hidden as they can interfere with the integrity of my JSON data

Whenever I make an AJAX call to a PHP script that outputs JSON, fatal errors in the PHP code ruin my beautifully formatted JSON output. The JSON string ends up being prefixed with ↵Fatal error: Call to undefined function iDontExist() in /path/to/place/w ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

Transmitting real-time updates from Server to Client through Ajax communication

Currently, I am utilizing an UpdatePanel to trigger a button click event that saves over 100 files to a specific folder. My goal is to have the server inform the client about the status and count of files being saved. protected void btnSave_Click(...){ ...

Creating a bespoke validation in AngularJS to verify if the selected date falls within a specific range of weekdays

Hey there! I'm looking to enhance the validation process for a date input field in a unique manner. Currently, my default validation setup looks like this: <div> <input type="text" name="firstName" ng-model="appointmentForm.firstName" ng- ...

What is the best way to control the iteration of a JavaScript 'for' loop based on specific conditions?

I need help with controlling the iteration of a 'for' loop in Javascript. Here is the code snippet: for (var j=0; j < number; j++){ $('#question').empty; $('#question').append('' + operand1[j], operator[j ...

Does the unique identifier of the element remain constant in jQuery?

For example: $("#savenew").live('click', function(e) { var user=<?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data:{user: user} , ...

Is there a never-ending loop caused by a jquery/jqtouch getJSON call?

I'm currently working on my first JQTouch application. I've encountered an issue where, upon transitioning from #login to #home, a JSON ajax call is triggered successfully but it seems that the pageAnimationEnded event gets stuck in an infinite l ...