javascript - 同步 AJAX 调用如何导致内存泄漏?

标签 javascript ajax jquery

我明白了this反对使用同步 ajax 调用的一般建议,因为同步调用会阻止 UI 呈现。

通常给出的另一个原因是同步 AJAX 的内存泄漏问题。

来自MDN文档-

Note: You shouldn't use synchronous XMLHttpRequests because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests. The only exception is that synchronous requests work well inside Workers.

同步调用如何导致内存泄漏?

我正在寻找一个实际的例子。 任何有关此主题的任何文献的指针都会很棒。

最佳答案

如果正确实现 XHR per spec ,那么它就不会泄漏:

An XMLHttpRequest object must not be garbage collected if its state is OPENED and the send() flag is set, its state is HEADERS_RECEIVED, or its state is LOADING, and one of the following is true:

It has one or more event listeners registered whose type is readystatechange, progress, abort, error, load, timeout, or loadend.

The upload complete flag is unset and the associated XMLHttpRequestUpload object has one or more event listeners registered whose type is progress, abort, error, load, timeout, or loadend.

If an XMLHttpRequest object is garbage collected while its connection is still open, the user agent must cancel any instance of the fetch algorithm opened by this object, discarding any tasks queued for them, and discarding any further data received from the network for them.

因此,在您点击 .send() 之后,XHR 对象(及其引用的任何对象)都不受 GC 的影响。然而,any error or success will put the XHR into DONE state并且它再次受到 GC 的影响。 XHR 对象是同步的还是异步的根本无关紧要。如果再次出现长同步请求,这无关紧要,因为在服务器响应之前,您只会卡在发送语句上。

然而,根据this slide它至少在 2012 年的 Chrome/Chromium 中没有正确实现。根据规范,不需要调用 .abort(),因为 DONE 状态意味着 XHR 对象应该已经是正常的 GCd。

我找不到任何证据来支持 MDN 声明,我已经通过 Twitter 联系了作者。

关于javascript - 同步 AJAX 调用如何导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364992/

相关文章:

javascript - 有没有比 for(for()) 更快的方法来在多维数组中查找值并返回其所有索引?

javascript - WKUserScript在iOS10中不调用,但在iOS9中有效

PHP从网页A触发,从网页B的数据库中加载内容

javascript - 通过拖动移动动态创建的 DIV

javascript - 在 Bootstrap Modal Close 上取消绑定(bind)现有功能

javascript - 在评估之前比较数学方程 javascript

javascript - React Formik 不适用于数字输入

javascript - 如何使用 javascript 打印 Canvas 内容

javascript - jquery ajax过滤器链

javascript - 根据 AJAX 请求向行添加表类/删除表类