Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I reuse XmlHttpRequest objects?

Tags:

From what I understand, it's a best practice to reuse XmlHttpRequest objects whenever possible. Unfortunately, I'm having a hard time understanding why. It seems that by trying to reuse XHR objects you increase your code complexity and you introduce possible browser incompatibilities. So why do so many people recommend it?

After some research, I was able to come up with this list of possible explanations:

  1. Fewer objects created means less garbage collection
  2. Reusing XHR objects reduces the chance of memory leaks
  3. The overhead of creating a new XHR object is high
  4. The browser is able to perform some sort of network optimization under hood

But I'm still a bit skeptical. Are any of these reasons actually valid? If not, what is a valid reason?

like image 437
Xavi Avatar asked Apr 21 '10 06:04

Xavi


People also ask

Can XMLHttpRequest be reused?

I recommend to use multiple XHR objects. With one global xhr object, your application can only deal with one request at a given time. It's also error-prone (eg. XMLHttpRequest launches multiple times without initiating the onreadystatechange function).

What for XMLHttpRequest object is used?

The XMLHttpRequest object is used to exchange data with a server behind the scenes. The XMLHttpRequest object is the developers dream, because you can: Update a web page without reloading the page. Request data from a server after the page has loaded.

What is the purpose of XMLHttpRequest in AJAX?

XMLHTTPRequest is basically used in Ajax programming. It retrieve any type of data such as json, xml, text etc. It request for data in background and update the page without reloading page on client side. An object of XMLHTTPRequest is used for asynchronous communication between client and server.

Do I need to close XMLHttpRequest?

Yes, if you haven't tricked your server to keep it alive, it will be closed after the response is sent. Maybe you want to look for websockets. But if you don't want to play with those, just create a new HttpRequest for each of your "request".


1 Answers

There are a whole host of problems relating to the number of open connections you can have at any one time; often this is imposed at a browser level as in all versions of Internet Explorer (IE6 allows 2, IE7 allows 2, IE8 allows 4), often this is imposed by server throttling and sometimes this is imposed by Internet Service Providers.

If you have a large number of distinct XmlHttpRequest objects in one script, and for some reason some of their connections have not closed properly or have not been GC'd, you may run into difficulty opening new connections and have absolutely no idea what is going wrong.

That and all of the reasons you mention.

like image 53
Finbarr Avatar answered Sep 20 '22 08:09

Finbarr