Dynamic script generation and memory leaks

An interesting piece by Neil Fraser shows that using JSON-P with generated script nodes can be quite a memory leak. Normally you'd add information returned from an API in JSON-P with a generated script node:

JAVASCRIPT: 
script = document.createElement('script');
script.src = 'http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F';
script.id = 'JSONP';
script.type = 'text/javascript';
script.charset = 'utf-8';
// Add the script to the head, upon which it will load and execute.
var head = document.getElementsByTagName('head')[0];
head.appendChild(script) 

 

The issue there is that you clog up the head of the document with lots of script nodes, which is why most libraries (like the YUI get() utility) will add an ID to the script element and remove the node after successfully retrieving the JSON data:

JAVASCRIPT: 

var script = document.getElementById('JSONP');
script.parentNode.removeChild(script);

 

 

The issue with this is that browsers do remove the node but fail to do a clean garbage collection of the JavaScript at the same time. This means to cleanly remove the script and its content, you need to also delete the properties of the script by hand:

JAVASCRIPT: 

// Remove any old script tags.
  var script;
  while (script = document.getElementById('JSONP')) {
    script.parentNode.removeChild(script);
    // Browsers won't garbage collect this object.
   // So castrate it to avoid a major memory leak.
    for (var prop in script) {
      delete script[prop];
    }
  }

 

from :http://ajaxian.com/archives/dynamic-script-generation-and-memory-leaks

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值