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

你可能感兴趣的:(JavaScript,jsonp,json,cgi,yui)