Dynamic script generation and memory leaks

文章讨论了使用JSON-P和动态生成的脚本节点时可能出现的内存泄漏问题。为避免浏览器中累积大量未清理的JavaScript对象导致内存泄漏,作者建议不仅要移除脚本节点,还要手工删除脚本对象的所有属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值