Conditional Compilation Comments

Modified on 2009/12/14 20:12 by Stephen Walther — Categorized as: Uncategorized

AjaxMin supports only a subset of conditional compilation comments. The @cc_on, @if, and @set statements are supported – it’s where they are in your code that determines whether or not they will be passed through to the output.

In general, statement-level conditional comments are supported. For instance, if you had the following code:

var ie = false;
/*@cc_on
ie = true;
@*/
alert(ie ? "Internet Explorer" : "NOT Internet Explorer");

It will get minified to:

var ie=false;/*@cc_on ie=true;@*/alert(ie?"Internet Explorer":"NOT Internet Explorer")

This is because the conditional-compilation comment starts at a statement boundary and only contains whole statements within it.

There is also a special-case scenario in which the var-statement can specify the initializer of a variable within conditional-compilation comments. This is useful for defining IE-specific values, like:

var ie/*@cc_on = 1 @*/;
alert(ie ? "Internet Explorer" : "NOT Internet Explorer");

which reduces to:

var ie/*@cc_on=1@*/;alert(ie?"Internet Explorer":"NOT Internet Explorer")

The rule here is that both the equals-sign and the initializer – but nothing else – must be included in the conditional-compilation comment. Anything else will be ignored.

Conditional-compilation comments in general are not supported by AjaxMin within JavaScript expressions. However, if a conditional-compilation comment is encountered inside an expression, and the comment contains only a single conditional-compilation variable reference, the comment will be retained. Anything else and it will be ignored. So for instance:

//@set @fourteen = 14
var fourteen = /*@fourteen @*/;
alert(/*@_jscript_version @*/);

will reduce to:

/*@set@fourteen=14@*/var fourteen=/*@fourteen@*/;alert(/*@_jscript_version@*/)

The above code will obviously not work in non-IE browsers, but it is just a simple example to illustrate how conditional-compilation comments within expressions can only contain references to variables in order to be retained in the output.

However:

var isMSIE = /*@cc_on!@*/0;

Will have the comment ignored and simply become:

var isMSIE=0

because the comment contains an operator and not a variable reference. Remember the general rule: use conditional-compilation comments at a statement level and AjaxMin should always retain them.