Javascript Reference
Categories: ConditionalCompilation

javascript ConditionalCompilation Description

@March 15, 2008, 1:22 a.m.
@cc_on, @if, @end, @setFirefox/Netscape/NN n/a IE 4(Win) ECMA n/a

IE for Windows includes a scripting feature called conditional compilation. It is a mode that, once turned on via the @cc_on statement, allows JScript statements to run under conditions that are testable within this conditional environment. If you surround conditional compilation statements by JavaScript comments, the conditional statements run only in IE 4 or later for Windows, while not conflicting with other browsers.

The "conditional" part comes from numerous global properties (all preceded with the @ symbol) that reveal environmental properties, such as script engine version, operating system, and CPU type. All of this information is available from the navigator object's properties on a wide range of browsers, so this is not unique information available only to this conditional environment.

To engage conditional compilation, include the following statement in your script:

/*@cc_on @*/

This is a one-way toggle: once the mode is turned on, it can't be turned off in the current page.

The following fragment shows how the @if and related statements display some environmental information in the window's status bar if the browser is running JScript Version 5.6 or later (IE 6 or later):

/*@cc_on @*/
/*@if (@_jscript_version>= 5.6 && @_x86)
    status = "Now running JScript version " + @_jscript_version + 
    " with Intel inside.";
   @else @*/
    status = "Have a nice day.";
/*@end @*/ 

The @set statement lets you assign a numeric or Boolean value (no strings) to a variable (a variable with an @ prefix) within a conditional compilation section:

@set @isOK = @_win32

Once initialized, that variable (including its otherwise unacceptable identifier) can be used in script statements throughout the page. Note that the Visual Basic-inspired syntax of @ statements in conditional compilation statements does not permit semicolons at the end of statements.

On the one hand, conditional compilation could be useful for IE-only deployment to screening older IE versions from new language features that would generate compilation errors (such as try-catch constructions) because such statements compile only under very controllable version situations. In a multibrand browser development shop, however, at most you might find application for IE-only debugging purposes, but probably not for actual application deployment.

 
Example

See the discussion above.


Powered by Linode.