【问题标题】:Memory leak in jQuery AjaxjQuery Ajax 中的内存泄漏
【发布时间】:2012-09-19 13:42:11
【问题描述】:

我遇到了 jQuery.ajax() 的内存泄漏。我遵循了herehere 的建议,但仍然看到内存泄漏。我实际上是在尝试用我自己的 API 替换 Google Visualization API,因为 GV API 也会泄漏内存。这是我的代码的 sn-p:

RiseVision.Common.Visualization.Query = function(url) {
    this.baseURL = url + "&tqx=responseHandler:setResponse";
    this.url = this.baseURL;
}
RiseVision.Common.Visualization.Query.prototype.send = function(callback) {
    var self = this;

    this.callback = callback;
    this.hasResponded = true;
    this.timerID = setInterval(function() {
        if (self.hasResponded) {
            self.hasResponded = false;
            self.sendQuery();
        }
    }, this.refreshInterval);
}
RiseVision.Common.Visualization.Query.prototype.sendQuery = function() {
    var request = $.ajax({ 
        url: this.url,
        context: this,
        jsonpCallback: "setResponse",
        dataType: "jsonp",
        success: function(json) {
            var response = new RiseVision.Common.Visualization.QueryResponse(json);

            if (json.sig != null) {
                this.url = this.baseURL + ";sig:" + json.sig;
            }

            if ((response.getStatus() == "error") && (response.getReasons() == "not_modified")) {
            }
            else {
                this.callback(response);
            }

            response = null;
            this.hasResponded = true;
        }
    });

    //This is supposed to mitigate the memory leak.
    request.abort = null;
    request = null;
}

我正在使用 jQuery 1.8。 refreshInterval 为 1 秒,因为它正在提取实时数据。我在 Chrome 的任务管理器中看到的是内存逐渐增加。大约 5 分钟后,垃圾收集似乎开始了,内存下降了。问题是内存没有下降到它开始时的相同水平。例如,内存从 50K 开始,然后逐渐增加到 60K,然后垃圾收集开始,内存下降到 52K。现在它增加到 62K,然后下降到 54K。等等。最终,这会使浏览器崩溃。

我尝试使用 setTimeout 而不是 setInterval。这似乎更糟。我已经尝试将成功处理程序放入它自己的函数中。没有帮助。

这是一个 jsfiddle 来说明问题 - http://jsfiddle.net/aADXq/7/

有什么建议吗?

谢谢。

【问题讨论】:

标签: jquery callback google-visualization


【解决方案1】:

将 ajax 请求中的数据类型更改为“文本”,然后使用 json_parse.js 解析结果字符串。这个库不使用 eval 递归解析 json,这会占用你的内存。

【讨论】:

  • jQuery 不使用eval 来解析 JSON。
猜你喜欢
  • 1970-01-01
  • 2012-10-25
  • 2023-04-08
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
相关资源
最近更新 更多