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

React component stuck in endless loop due to Intersection Observer

My goal is to track the visibility of 3 elements and update state each time one of them becomes visible. Despite trying various methods like other libraries, useMemo, useCallback, refs, etc., I still face challenges with my latest code: Endless loop scenar ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead ...

I'm having trouble understanding why I keep encountering this error message: "SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…"

I am in the process of implementing a download button feature that will allow users to download a document from my node.js server. Check out this stylish button: https://i.stack.imgur.com/s4CjS.png For the front-end, I am utilizing Angular as the fram ...

The functionality of react-router-dom's NavLink isActive feature seems to be unreliable

We are currently immersed in a React.js project. I am in the process of setting up multiple pages using react-router-dom and my goal is to alter the active icon by using NavLink. The icon+sel signifies the active page. render() { const oddEvent = (mat ...

Load the index file using any URL parameter in the Express.js Router's "catchall" feature

I have a simple setup for my project, including server.js file in the root directory with the following code: app.use('/', express.static(__dirname + '/public/')); In addition, there is a public folder containing index.html, styles, a ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

What is the best way to obtain root access and utilize disk usage (du) within the main process of Electron?

In the process of developing a macOS application with the help of Electron, I encountered an issue. Attempting to execute the following command from the main process using ipcMain and NodeJS's exec: // Navigating to a directory and utilizing disk us ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Issue encountered while transferring files between a web platform and an API

Currently, I am working on two separate projects. The first project involves a website where users can upload files, and the second project is an API designed for file uploads due to the limitations of the old website. I am utilizing Laravel (6) to develo ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

Customizing Ext JS/Sencha Chart framework based on certain conditions

As someone who is new to Ext JS and Sencha charts, I have encountered a challenge with one of the charts in our application. Specifically, I needed to hide the dashes on the X-Axis of that particular chart. Our application is built using Ext JS version 5.1 ...

Can I obtain a dictionary containing the connections between labels and phrases from the classifier?

I've implemented a LogisticRegressionClassifier using the natural library for node: const natural = require('natural'); const classifier = new natural.LogisticRegressionClassifier(); classifier.addDocument('category1', 'sent ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

Revise tax classification for international customers of the company in WooCommerce

I am currently facing an issue in WooCommerce where I need to set a different tax class for company users with billing addresses outside of Germany. Normally, the tax rate is always 19%, but in this specific case, I require it to be set at 0%. To achieve t ...

Adjusting value of one input field according to the content of another text field in an

Just starting out with Angular and I am looking to dynamically change the value of a hidden input field called 'cc_card' based on the first digit entered in another input field called 'cc_number'. For example, if the user enters 5 in &a ...