When does an xmlHttpRequest object parse serialized XML into a DOM during its lifecycle?

When a JavaScript code with xmlHttpRequest.responseXML() runs, it creates a DOM Document object from the XML-structured HTTP response body.

Have you ever wondered at what moment the XML string is turned into the DOM Document by an xmlHttpRequest object?

There are two possibilities:

  • The parsing could take place when responseXML() is executed. This way, resources are not wasted on converting the XML string until it's actually needed.

  • Alternatively, the parsing might occur once the HTTP response is received. If the server sends back a text/xml content-type, it indicates that XML was requested and likely needs to be converted into a DOM for proper use of the data received.

Both options have their advantages, but my inclination is that the XML string is parsed only upon calling responseXML.

So, when exactly does the parsing of the XML string happen?

I ask because I want to compare browser performance in deserializing XML versus JSON data.

Answer №1

It would be ideal to parse the stream as it is being received rather than waiting until the entire response is complete or the responseXml property is called. This would eliminate unnecessary delays in building the DOM after all bytes have been received. A more efficient approach would involve building the DOM concurrently with receiving the stream, so that once the stream is complete, the DOM is immediately ready for usage.

An important consideration is that MSXML does not generate a DOM if the Content type does not specify an XML type, while Mozilla's implementation allows you to override this and treat the content as XML regardless of the indicated Content-Type.

If the DOM is only parsed when the property is accessed, there would be no need for the above complexities. The property could simply attempt to parse the content directly. It is because a DOM can be constructed on-the-fly as content is received that these considerations come into play.

Answer №2

It wouldn't shock me if this varies depending on the browser. How about we analyze all three?

Answer №3

When using Chrome, the DOM is generated and parsed upon calling responseXML().

Here is the code snippet for the function:

Document* XMLHttpRequest::responseXML(ExceptionCode& ec)
{
    if (responseTypeCode() != ResponseTypeDefault && responseTypeCode() != ResponseTypeText && responseTypeCode() != ResponseTypeDocument) {
        ec = INVALID_STATE_ERR;
        return 0;
    }

    if (m_state != DONE)
        return 0;

    if (!m_createdDocument) {
        if ((m_response.isHTTP() && !responseIsXML()) || scriptExecutionContext()->isWorkerContext()) {
            // According to W3C specification.
            m_responseXML = 0;
        } else {
            m_responseXML = Document::create(0, m_url);
            // TODO: Implement setting Last-Modified.
            m_responseXML->setContent(m_responseBuilder.toStringPreserveCapacity());
            m_responseXML->setSecurityOrigin(document()->securityOrigin());
            if (!m_responseXML->wellFormed())
                m_responseXML = 0;
        }
        m_createdDocument = true;
    }

    return m_responseXML.get();
}

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

Tips for effectively redirecting traffic to another website

Is there a way to redirect someone from a page URL like example.com/2458/233 to example2.com/2458/233? The first URL contains only a file that redirects to the other domain. Can anybody provide instructions on how to achieve this process? To clarify furt ...

Manage the material-ui slider using play and pause buttons in a React JS application

I have a ReactJS project where I am utilizing the continuous slider component from material-ui. My goal is to be able to control the slider's movement by clicking on a play button to start it and stop button to halt it. Below is the code snippet of th ...

Are the files selected by the user not displaying properly in the URL?

I'm currently working on a project using PhoneGap where I am facing an issue with uploading files and adding all file names to the parameters. The desired format is: http://www.example.com/uplaod.html?file=file1,file2,file3 To achieve this, I have a ...

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Unable to navigate beyond the boundaries of an app

I am currently facing an issue with my authentication service where it redirects to the identity server in case of certain errors. I attempted to achieve this using window.location.href = environment.authCodeFlowIssuer;, however, an error occurred: Ref ...

When a user hovers over an li element, jQuery will dynamically adjust the width of the element based

<ul class="level0"> <li class="level1" id="cat2441"></li> <li class="level1" id="cat2450"></li> <li class="level1" id="cat2455"></li> </ul> <div class="alles-zwei" id="new-cat2441"></div> <div ...

Failure encountered when attempting to load JSON data into datalist

I've been trying to incorporate inputs into a datalist in two different ways. However, I've encountered an issue with the first method not working properly. --> Check it out on bootlply var dataList = document.getElementById('json-datalist ...

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

Issue with the file input functionality in MySQL Ajax Table Editor

Currently, I am utilizing the MySQL Table editor from this project: , in order to manage MySQL tables by adding, updating, and deleting data. stop_list(stop_list_id,full_names,nationality,gender,document_type,document_number,date_of_birth,hair_colour,heig ...

Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks: Check if a given array can represent Preorder Traversal of Binary Search Tree This is the algorithm they provided: 1) Cr ...

What is the proper way to include a URL when submitting an AJAX form?

When I try to call a servlet using HTML, jQuery and Ajax by submitting a form, I keep getting a 404 error saying the resource cannot be found. My project is built with Maven. The Servlet is located in the src/main/java package under : com.mycompany.sample ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

I encounter issues with my fetch request as it is denied while attempting to access the HTML content from the specified

I'm currently working on a project in my express app where I need to retrieve the html code of multiple urls. However, I keep encountering this error: reject(`new FetchError(request to ${request.url}` failed, reason: ${err.message}, 'system' ...

The text is not appearing properly in an HTML file due to issues with

Hi trying to display the text received from the controller's scope. Here's what I have attempted: HTML: <div ng-repeat="item in sResults"></div> Controller JavaScript: $scope.sResults = []; function App( ){ var Label ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

Warning: An error occurred while trying to retrieve data for table id=DataTables_Table_0

I encountered a warning message while using Datatables in Laravel: DataTables warning: table id=DataTables_Table_0 - Ajax error. For more details about this issue, please visit http://datatables.net/tn/7 I'm unable to retrieve JSON data from my ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...