Conditional compilation is activated by using the @cc_on statement inside your script, or by directly using an @if or @set statement that are part of the logic of CC. Here's an illustrative example:
If you're using IE (of any version), you should see the first document.write() rendered, and for IE5+, the following two document.write() as well (since JScript 5 is supported by IE5+). The last document.write() method is served only to non IE5+ browsers, whether it's Firefox, Opera, IE4, you name it. Conditional compilation relies on tag teaming with the comment tag, similar to in Conditional Comments, to ensure it works harmoniously in all browsers.
When working with Conditional Compilation, it's best to first activate it via the @cc_on statement, as only then can you also include comment tags in your script in a way that ensures browser compatibility, as shown in the example above.
@if, @elif, @else, and @end statements
So with the formalities out of the way, here are the conditional statements at your disposal for conditional compilation:
Lets see some "eccentric" examples now.
if else logic (IE exclusive)
/*@cc_on @if (@_win32) document.write("OS is 32-bit. Browser is IE."); @else document.write("OS is NOT 32-bit. Browser is IE."); @end @*/
Here the entire script is only rendered by IE browsers and ignored by all else, and depending on the bit of your OS, a different message is shown. Contrast that with the next example...
if else logic II (other browsers inclusive)
/*@cc_on /*@if (@_win32) document.write("OS is 32-bit, browser is IE."); @else @*/ document.write("Browser is not IE (ie: is Firefox) or Browser is not 32 bit IE."); /*@end @*/
By manipulating the comment tag, the "else" part in this example will get picked up by all non IE browsers such as Firefox, plus non 32 bit IE as well. Study the comments until your head spins, and you'll see the logic. :)
if, elseif, else logic (IE exclusive)
Moving on, time for the full Monty:
/*@cc_on @if (@_jscript_version >= 5) document.write("IE Browser that supports JScript 5+"); @elif (@_jscript_version >= 4) document.write("IE Browser that supports JScript 4+"); @else document.write("Very old IE Browser"); @end @*/
if, elseif, else logic II (other browsers inclusive)
/*@cc_on /*@if (@_jscript_version >= 5) document.write("IE Browser that supports JScript 5+"); @elif (@_jscript_version >= 4) document.write("IE Browser that supports JScript 4+"); @else @*/ document.write("Non IE Browser (one that doesn't support JScript)"); /*@end @*/
Sane deal here. In this 2nd example of the 2nd set, the final "else" statement gets picked up by non IE browsers.
- Conditional Compilation overview
- Conditional Compilation variables
- Conditional Compilation example- try/catch statements