JavaScript Legacy — Optimization through Conditional Compilation

This might be an ultimate optimization weapon. And it might even be considered as a non-hack, not-a-trick, etc.

As an good and simple example, in jQuery there is a function to make and return XHR, depending on which is the current browser host.

Good logic, simple implementation. Yes, but… This function is called a lot and each time , precious microseconds are wasted to find out which version is to be used, made and returned.
And. Each time the result is the same, because this keeps on being called in the same browser session. What first springs out as an obvious optimization is this :

The condition above is evaluated only when the whole object in which ‘xhr’ resides gets evaluated and made. In jQuery case, this is hopefully only once, when jQuery is made in its closure.

But there is one more “ultimate” version I can think of. Even more optimized version we can write. This time we will use Microsoft JavaScript conditional compilation feature. It is part of javascript

    only

when IE is the host browser.

What is happening here? First we defined xhr() version for all the browsers but IE

Then comes the comment bellow it , which contains Microsoft JavaScript syntax that switches
on, the conditional compilation : “//@cc_on”. This also works inside another comment syntax and if in IE, uitside of comments, anywhere in javascript code.
So, if this comment is inside IE javascript, it will be made part of the source code, effectively overriding the previous version of xhr(). In IE the code will now look like this:

The second version of xhr() will overwrite (aka override) the first version. The first version is erased, the second now exist, and is being used when called.

There you have it: an example of ultimate optimization. I very much doubt I have invented this. But neverhelles I will suggest it as an very effective mehanism for cross browser libraries.

Update 2009 Nov 25

There is one very elegant way to use condtional “compilation” to distinguish between IE and non-IE code:

Simple and effective. In IE the above is parsed into :

While everywhere else code is parsed as :

Arguably this is more code and also, this is if/else which is always executed but still in some situations this is very valid, and maybe not a “trick”.
Alternatively, you are wellcome to use the ultimate in JS conditional “compilation” :

Enjoy ;)

Mask of Happines
Mask of Happines

6 thoughts on “JavaScript Legacy — Optimization through Conditional Compilation”

Comments are closed.