我正在尝试重写一些Ajax代码,以使其更适合自动完成需求。在这种情况下,有时您必须中止先前的请求,即xhr.abort(),因此重用该XMLHttpRequest对象(在此我简称为xhr)感觉很自然。

我试图了解重用XMLHttpRequest对象是个好主意。您会看到哪些利弊?

PS:此重写将使用本机ES6样式的Promise,因此它只能在较新的Web浏览器中运行。

最佳答案

只是@Bergi建议的计时测试:

function initCache(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url); xhr.send();
    console.log("Initialized cache");
}

function reuseXhr(url, numLoops) {
    var xhr = new XMLHttpRequest();
    for (var i=0; i<numLoops; i++) {
        xhr.open("get", url); xhr.send();
    }
    xhr.abort();
}

function newXhr(url, numLoops) {
    var xhr;
    for (var i=0; i<numLoops; i++) {
        xhr = new XMLHttpRequest();
        xhr.open("get", url); xhr.send(); xhr.abort();
    }
}
function testIt() {
    var url = "http://urlwithcors.com/"; // Pseudo-URL with CORS enabled
    var numLoops = 1000;
    initCache(url);
    setTimeout(function(){
        console.time("reuse"); reuseXhr(url, numLoops); console.timeEnd("reuse");
        console.time("new"); newXhr(url, numLoops); console.timeEnd("new");
    }, 5000);
}
testIt();


在Chrome中,这里的结果是:

test-xhr-reuse.js:6 XHR finished loading: GET ...
reuse: 510.000ms
new: 386.000ms


因此...在慢速PC上每次通话0.1毫秒,这是不值得的麻烦...

现在等待-重用xhr甚至更慢...不值得。 ;-)

多一点测试表明完全没有区别。这只是一个偶然的问题。

关于javascript - 重用XMTHttpRequest对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27888471/

10-09 22:19
查看更多