IE下的JS条件编译

来源:互联网 发布:ajax解析json数组 编辑:程序博客网 时间:2024/06/05 15:33

 

In IE, there is a little known feature called conditional compilation. Supported since IE4, this feature starting getting some attention when it began showing up in some Ajax related JavaScripts. An absolute form of object detection, conditional compilation lets you dictate to IE whether to compile certain parts of your JScript or JavaScript code depending on predefined and user defined conditions. Think of it as conditional comments for your script that can also be molded to work gracefully with non IE browsers as well.

 

 

Syntax Overview

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:

<script type="text/javascript">/*@cc_ondocument.write("JScript version: " + @_jscript_version + ".<br>");   /*@if (@_jscript_version >= 5)      document.write("JScript Version 5.0 or better.<br //>");      document.write("This text is only seen by browsers that support JScript 5+<br>");   @else @*/      document.write("This text is seen by all other browsers (ie: Firefox, IE 4.x etc)<br>");   /*@end@*/</script>

Example:

JScript version: 5.7.
JScript Version 5.0 or better.
This text is only seen by browsers that support JScript 5+

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:

  •  @if
  • @elif
  • @else
  • @end

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.

 

===================================================================

On the previous page you saw some strange looking variables such as @_win32. These are predefined conditional compilation variables you can use to test for certain aspects of IE or the computer at large:

Predefined conditional compilation variablesVariableDescription@_win32Returns true if running on a Win32 system, otherwise NaN.@_win16Returns true if running on a Win16 system, otherwise NaN.@_macReturns true if running on an Apple Macintosh system, otherwise NaN.@_alphaReturns true if running on a DEC Alpha processor, otherwise NaN.@_x86Returns true if running on an Intel processor, otherwise NaN.@_mc680x0Returns true if running on a Motorola 680x0 processor, otherwise NaN.@_PowerPCReturns true if running on a Motorola PowerPC processor, otherwise NaN.@_jscriptAlways returns true.@_jscript_buildThe build number of the JScript scripting engine.@_jscript_versionA number representing the JScript version number in major.minor format.

IE4 supports JScript 3.x
IE5.x supports JScript  5.5 or less
IE6 supports JScript 5.6

The version number reported for JScript .NET is 7.x.

@_debugReturns true if compiled in debug mode, otherwise false.@_fastReturns true if compiled in fast mode, otherwise false.

In most cases, you probably will be limited to just using @_win and @jscript_build:

/*@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@*/

User defined Variables

You can also define your own variables to use within the conditional compilation block, with the syntax being:

@set @varname = term

Numeric and Boolean variables are supported for conditional compilation, though strings are not.  For example:

@set @myvar1 = 35@set @myvar3 = @_jscript_version

The standard set of operators are supported in conditional compilation logic:

  • ! ~
  • * / %
  • + -
  • << >> >>>
  • < <= > >=
  • == != === !==
  • & ^ |
  • && |

You can test if a user defined variable has been defined by testing for NaN:

@if (@newVar != @newVar)//this variable isn't defined.

This works since NaN is the only value not equal to itself.

 

==============================================================

In the beginning of the tutorial, I mentioned how conditional compilation got a boast to its profile when it started showing up in some Ajax related JavaScripts. I'll show you what I mean here. A Ajax script usually contains a central function for testing support for the objects needed to make asynchronous requests in IE and Firefox:

Typical ajax function:

function HttpRequest(url, parameters){var pageRequest = false //variable to hold ajax object   if (window.XMLHttpRequest) // if Mozilla, Safari etc      pageRequest = new XMLHttpRequest()   else if (window.ActiveXObject){ // if IE      try {      pageRequest = new ActiveXObject("Msxml2.XMLHTTP")      }       catch (e){         try{         pageRequest = new ActiveXObject("Microsoft.XMLHTTP")         }         catch (e){}      }   }   else   return false}

Most people think the "try/catch" statements will gracefully test for Ajax support, though unfortunately that's not true. Browsers that do not support "throw/catch", such as IE4.x, will in fact choke on the above code and return an error. To overcome this, conditional compilation can be used to create a truly cross browser friendly Ajax processing function:

Truly cross browser ajax function:

function HttpRequest(url, parameters){var pageRequest = false //variable to hold ajax object/*@cc_on   @if (@_jscript_version >= 5)      try {      pageRequest = new ActiveXObject("Msxml2.XMLHTTP")      }      catch (e){         try {         pageRequest = new ActiveXObject("Microsoft.XMLHTTP")         }         catch (e2){         pageRequest = false         }      }   @end@*/if (!pageRequest && typeof XMLHttpRequest != 'undefined')pageRequest = new XMLHttpRequest()}

Using conditional compilation, the entire try/catch block is only rendered by IE5+, sparing browsers like IE4 or non IE browsers from trying to dicipher it. Firefox obviously will pick up on and use XMLHttpRequest instead. And there you have it- a truly cross browser ajax function!