Tuesday, 15 June 2010
Facebook StumbleUpon Twitter Google+ Pin It

Reversing Code Bloat with the JavaScript Knowledge Base

JavaScript libraries let developers do more with less code. But JavaScript libraries need to work on a variety of browsers, so using them often means shipping even more code. If JQuery has code to support XMLHttpRequest over ActiveX on an older browser like IE6 then you end up shipping that code even if your application doesn't support IE6. Not only that, but you ship that code to the other 90% of newer browsers that don't need it.

This problem is only going to get worse. Browsers are rushing to implement HTML5 and EcmaScript5 features like JSON.parse that used to be provided only in library code, but libraries will likely have to keep that code for years if not decades to support older browsers.

Lots of compilers (incl. (JSMin, Dojo, YUI, Closure, Caja) remove unnecessary code from JavaScript to make the code you ship smaller. They seem like a natural place to address this problems. Optimization is just taking into account the context that code is going to run in to improve it; giving compilers information about browsers will help them avoid shipping code to support marginal browsers to modern browsers.

The JavaScript Knowledge Base (JSKB) on browserscope.org seeks to systematically capture this information in a way that compilers can use.

It collects facts about browsers using JavaScript snippet. The JavaScript code (!!window.JSON && typeof window.JSON.stringify === 'function') is true if JSON is defined. JSKB knows that this is true for Firefox 3.5 but not Netscape 2.0.

Caja Web Tools includes a code optimizer that uses these facts. If it sees code like

if (typeof JSON.stringify !== 'function') { /* lots of code */ }

it knows that the body will never be executed on Firefox 3.5, and can optimize it out. The key here is that the developer writes feature tests, not version tests, and as browsers roll out new features, JSKB captures that information, letting compilers produce smaller code for that browser.

The Caja team just released Caja Web Tools, which already uses JSKB to optimize code. We hope that other JavaScript compilers will adopt these techniques. If you're working on a JavaScript optimizer, take a look at our JSON APIs to get an idea of what the JSKB contains.

If you're writing JavaScript library code or application code then the JSKB documentation can suggest good feature tests. And the examples in the Caja Web Tools testbed are good starting places.

No comments: