Dynamic script generation and memory leaks

In: web resources

28 Jul 2009

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:

  1. script = document.createElement(‘script’);
  2.   script.src = ‘http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F’;
  3.   script.id = ‘JSONP’;
  4.   script.type = ‘text/javascript’;
  5.   script.charset = ‘utf-8′;
  6.   // Add the script to the head, upon which it will load and execute.
  7.   var head = document.getElementsByTagName(‘head’)[0];
  8.   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:

  1. var script = document.getElementById(‘JSONP’);
  2. 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:

  1. // Remove any old script tags.
  2.   var script;
  3.   while (script = document.getElementById(‘JSONP’)) {
  4.     script.parentNode.removeChild(script);
  5.     // Browsers won’t garbage collect this object.
  6.     // So castrate it to avoid a major memory leak.
  7.     for (var prop in script) {
  8.       delete script[prop];
  9.     }
  10.   }

Read the whole post here

Comment Form

About this blog

This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.