javascript 重用 XMLHttpRequest 对象还是创建一个新对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11502244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reuse XMLHttpRequest object or create a new one?
提问by gom
I searched stackoverflow but got contradictory answers:
我搜索了 stackoverflow,但得到了相互矛盾的答案:
Why should I reuse XmlHttpRequest objects?
Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?
Ajax 密集型页面:重用相同的 XMLHttpRequest 对象还是每次都创建一个新对象?
Also, there's a recommendation on w3schools.com :
另外,在 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.
如果您的网站上有多个 AJAX 任务,您应该创建一个标准函数来创建 XMLHttpRequest 对象,并为每个 AJAX 任务调用它。
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
为什么有这个建议?我在我的页面上使用全局 XMLHttpRequest 对象来处理所有 Ajax 任务。
回答by Rob W
You misunderstood W3School's recommendation. I'll highlight the relevant part:
你误解了 W3School 的推荐。我将重点介绍相关部分:
If you have more than one AJAX task on your website, you should create ONE standard functionfor creating the XMLHttpRequest object, and call this for each AJAX task.
如果您的网站上有多个 AJAX 任务,您应该创建一个标准函数来创建 XMLHttpRequest 对象,并为每个 AJAX 任务调用它。
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.
它说您使用一个 AJAX 函数来获取请求。该功能将处理 IE 与其他浏览器之间的不一致。XMLHttpRequest
在符合标准的浏览器和ActiveXObject
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).
我建议使用多个 XHR 对象。使用一个全局 xhr 对象,您的应用程序在给定时间只能处理一个请求。它也容易出错(例如,XMLHttpRequest 多次启动而没有启动 onreadystatechange 函数)。
W3schools meant something like:
W3schools 的意思是这样的:
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
.
尽管最好创建一个处理请求的函数,例如jQuery.ajax
.
回答by UltraInstinct
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.
最好为您制作的每个 XHR 使用不同的对象。即使有办法做到,也要避免它!为每个请求创建新对象没有问题。如果您担心内存泄漏或类似问题,请不要担心,它们都已正确地进行了 GC。
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.
如果您的网站上有多个 AJAX 任务,您应该创建一个标准函数来创建 XMLHttpRequest 对象,并为每个 AJAX 任务调用它。
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();
}
回答by Utkanos
The recommendation you highlight is saying you should have one FUNCTION which handles AJAX, rather than specifically one XMLHTTPRequest object.
您强调的建议是说您应该拥有一个处理 AJAX 的 FUNCTION,而不是专门的一个 XMLHTTPRequest 对象。
I would use a different one for each question.
我会为每个问题使用不同的答案。
The common argument against this concerns the overheads involved in setting up XHRs. However this is going to be pretty much negligible in any site that uses AJAX as it was intended (i.e. not as a labouring substitute for web sockets) and, in any case, much of the same overheads would apply with re-using an XHR. You'd still have to open the connection, fire it, attach listeners etc.
反对这一点的常见论点涉及设置 XHR 所涉及的开销。然而,在任何按照预期使用 AJAX 的站点中,这几乎可以忽略不计(即不是作为 Web 套接字的劳动替代品),并且在任何情况下,重用 XHR 都会产生相同的开销。您仍然必须打开连接,启动它,附加侦听器等。
Browsers vary in terms of how many connection gateways are allowed at a given time, so it's up to the browser to control what XHRs can do what. In other words, you don't have to worry about managing this aspect.
浏览器在给定时间允许的连接网关数量方面有所不同,因此由浏览器来控制 XHR 可以做什么。换句话说,您不必担心管理这方面。
Finally, there's nothing stopping you manually deleting the XHRs after you've used them, provided they are deletable (properties of an object rather than variables).
最后,没有什么可以阻止您在使用 XHR 后手动删除它们,前提是它们是可删除的(对象的属性而不是变量)。
回答by gom
From MDN Web Docs:
来自 MDN 网络文档:
If the httpRequest variable is used globally, competing functions calling makeRequest() can overwrite each other, causing a race condition. Declaring the httpRequest variable local to a closure containing the AJAX functions avoids this.
如果全局使用 httpRequest 变量,调用 makeRequest() 的竞争函数可能会相互覆盖,从而导致竞争条件。将 httpRequest 变量声明为包含 AJAX 函数的闭包的本地变量可以避免这种情况。
Source: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
来源:https: //developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
回答by Walter Vehoeven
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.
如果我最终在我自己的站点上生成 DOS,因为我向同一个 url 发送了多个请求,我可以使用 xhr.readyState 在发送下一个请求之前查看它有多忙,但是我还没有遇到这个问题。