Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest - freeing after use?

I'm writing a browser app that would be entirely AJAX-driven (first time in my life), that means:

  • it will be one page staying in the browser, loading program components as needed
  • browser history will be, well, none.
  • page will not be refreshed at all

My concern is what should I do about XMLHttpRequests, since I'm primarily C++ programmer, being taught that when you write a statement like

x = new XMLHttpRequest();

you need to delete it afterwards.

This question is entirely about memory management, whether this object, allocated with new stays in memory, even after it finishes it's "cycle" with readyState == 4 or is somehow released, freed, whatchacallit? Honestly, I have no idea at what point could it be freed, since the script creating these will be in HEAD and sit there potentially whole workday. Whether should I:

  • create one or several, reused objects of type XMLHttpRequest, program the app so that it won't need any more than this limit,
  • or it doesn't matter and I can allocate as many new XMLHttpRequests as I like?

Please include in your answers at what point and WHY those objects would be deleted, if they would at all, considering that the "frame" of my webpage will stay. Hope I made this question clear and thanks for any insightful answers.

EDIT:

Consider code (I removed many lines that were checking for unexpected return values for brevity) of an onClick event handler, that creates XMLHttpRequest and sends it:

function submitme(){  
  var p = document.getElementById('p'); //a text field being sent to server
  if(typeof p!='undefined' && p!=null){
    if(p.value!=""){
      //here XMLHttpRequest is created, this function
      //returns exactly object of this type or false, when failed
      var xhr=createXmlHttpRequestObject();
      if(xhr!=false){
        xhr.open("POST", "blablabla.php", true);
        xhr.onreadystatechange=function(){
          if(xhr.readyState==4){
             if(xhr.status==200){
               //result will be posted in this div below
               var adiv = document.getElementById('resultdiv');
               //extract the XML retrieved from the server
               xmlResponse = xhr.responseXML;
               //obtain the document element (the root element) of the XML structure
               xmlDocumentElement = xmlResponse.documentElement;
               //get the response text
               if(typeof adiv !='undefined' && adiv != null){
                  adiv.innerHTML=xmlDocumentElement.childNodes[0].firstChild.nodeValue;
               }
             }//end xhr.status
           }//end xhr.readyState
         };//end xhr.onreadystatechange
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         xhr.send(p.value);
       }//end xhr!=false
     }//end p.value!=""
   }//end typeof p!='undefined'
 }//end submitme()

When XMLHttpRequest object instance is created, if this handler is fired, it is referenced once by xhr variable until handler finishes to execute. At this point there are how many references to this object instance? If I understand articles linked in your answers correctly, the answer should be none, and browser just waits for this request to turn readystate==4, finish executing onreadystatechange function and object is unreachable? Please confirm.

like image 936
Kitet Avatar asked Feb 04 '14 13:02

Kitet


People also ask

What can I use instead of XMLHttpRequest?

The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Is XMLHttpRequest deprecated?

Synchronous request. Warning: Synchronous XHR requests often cause hangs on the web, especially with poor network conditions or when the remote server is slow to respond. Synchronous XHR is now deprecated and should be avoided in favor of asynchronous requests.

Is XMLHttpRequest same as AJAX?

XHR is the XMLHttpRequest Object which interacts with the server. Ajax technique in the nutshell leverages the XHR request to send and receive data from the webserver. This object is provided by the browser's javascript environment. It transfers the data between the web browser and server.

How do I check XMLHttpRequest status?

The read-only XMLHttpRequest. status property returns the numerical HTTP status code of the XMLHttpRequest 's response. Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors.


2 Answers

I have recently hit the same problem, and I have found all around the Internet that I should not have any concerns, because it is garbage collected. Well, you SHOULD have concerns, because it is quite easy to leave some references around, if you just got it work for the first time.

See this page:

http://javascript.info/tutorial/memory-leaks

and scroll down to "XmlHttpRequest..."

What it basically says:

IF you create a new xhr object every time (do not reuse them) AND capture each xhr object in the closure of the respective onreadystatechange callback THEN the xhr object will never be garbage collected, and the memory leak will ramp up.

To avoid this situation, use the this to access the xhr object (e.g. to check state), and get the xhr out of the closure.

like image 100
Zoltan K. Avatar answered Sep 21 '22 02:09

Zoltan K.


http://xhr.spec.whatwg.org/#garbage-collection - here is the answer to your question. This is part of specification (how it has to be implemented, but this is not 100% sure how it is implemented in all browsers), to understand it more deeply advice you to read the hole document

An XMLHttpRequest object must not be garbage collected if its state is OPENED and the send() flag is set, its state is HEADERS_RECEIVED, or its state is LOADING, and one of the following is true:

It has one or more event listeners registered whose type is readystatechange, progress, abort, error, load, timeout, or loadend.

The upload complete flag is unset and the associated XMLHttpRequestUpload object has one or more event listeners registered whose type is progress, abort, error, load, timeout, or loadend.

If an XMLHttpRequest object is garbage collected while its connection is still open, the user agent must terminate the request.

like image 45
Vlad Nikitin Avatar answered Sep 24 '22 02:09

Vlad Nikitin