Reuse XMLHttpRequest object or create a new one?

Viewed 21768

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.

5 Answers

I am using a pattern like this

var xhrSendBuffer = new Object();
function sendData(url, model) {
    if (!xhrSendBuffer[url]) {
        let xhr = new XMLHttpRequest();
        xhr.onloadend = xhrDone;
        xhr.error=xhrError;
        xhr.onabort = xhrAbborted;
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhrSendBuffer[url] = xhr;
    }

    xhrSendBuffer[url].send(JSON.stringify(model));
}

function xhrDone(e) {
    console.log(e);
}
function xhrError(e) {
    console.error(e);
}
function xhrAbborted(e) {
console.warn(e);
}

if I end up producing a DOS on my own site because I send to the same url multiple requests I could use the xhr.readyState to see how busy it is before sending the next request, however I have yet to encounter this as an issue.

Related