I searched stackoverflow but got contradictory answers:
Why should I reuse XmlHttpRequest objects?
Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?
Also, there's a recommendation on w3schools.com :
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
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).
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.
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
You misunderstood W3School's recommendation. I'll highlight the relevant part:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It says that you use one AJAX function to fetch requests. This function will deal with the inconsistencies between IE and other browsers. XMLHttpRequest
in standard-compliant browsers, and ActiveXObject
in IE.
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).
W3schools meant something like:
function createXHR() { try { return new XMLHttpRequest(); } catch (e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return new ActiveXObject("Msxml2.XMLHTTP"); } } } var xhr = createXHR(); xhr.open('get', '/test', true); xhr.send();
Although it's better to create a function which handles requests, such as jQuery.ajax
.
It is best to use different objects for each XHR you are making. Even if there's a way of doing it, avoid it! There's no problem with creating new object for each request. If you are worried about memory leak or something of that sort, do not worry, they are all properly GC`ed.
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It actually means that you have one function that creates a new object and returns it every time you call it. It something like:
function newXHR(){ return a new instance of XHR(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With