Jscript/javascript conditional Compilation

Source: Internet
Author: User
Tags comments contains functions include numeric variables variable try catch
javascript|js|jscript| Compilation | condition

Conditional compilation of jscript/javascript in IE

Author: JavaScript Kit
Translator: Zou (Sheneyan)
Translation Date:2006-02-12
English Original: Conditional Compilation of Jscript/javascript in IE
Copyright: I am only responsible for the Chinese part I have translated without the permission of JavaScript kit. Copyright belongs to the original author.

Sub-note: As before the article, I can only according to my understanding of the article translation out, but my own level is limited, many places may exist to the original misunderstanding or even misunderstanding, if possible, or read the original text.

Conditional Compilation Overview

In IE, there is a little-known feature called Conditional compilation (conditional compilation). Since IE4 began to support this feature, it has received some attention due to its presence in some Ajax-related JavaScript scripts. Conditional compilation, as an independent form of object judgment, allows IE to determine whether your JScript or JavaScript code-specific parts are compiled based on predefined or user-defined conditions. You can also think of it as a conditional comment for your code (contional comments, which will soon translate this article) so that your code can run smoothly on non ie browsing.

Syntax overview

Activate conditional compilation by using @cc_on in your script, or use the @if or @set, and so on as part of the CC logic. Here is a sample example:

<script type= "Text/javascript" >

/* @cc_on
document.write ("JScript version:" + @_jscript_version + ".<br>");
/ * @if (@_jscript_version >= 5)
document.write ("JScript version 5.0+.<br \/>");
document.write ("Only when browsers support jscript5+ can you see these words .<br>");
@else @*/
document.write ("When you use other browsers (such as Firefox, IE 4.x, etc.) when you see this line of text <br>");
/ * @end
@*/

</script>

Example:

Run Code Box
<script type= "Text/javascript" >/* @cc_ondocument. Write ("JScript version:" + @_jscript_version + ". <br/>"); /* @if (@_jscript_version >= 5) document.write ("JScript version 5.0+.<br/>"); document.write ("You can only see these words when the browser supports jscript5+.") <br/> "); @else @*/document.write ("When you use other browsers (such as Firefox, IE 4.x, etc.), you see this line of text." <br/> "); /* @end @*/</script>
[Ctrl + A ALL SELECT hint: You can modify some of the code, and then run]

If you use IE (any version), you should be able to see the output of the first document.write (), and if it is ie5+, the next two document.write () you can also see (because JScript 5 is supported from IE5). The last document.write () method is for other ie5+ browsers, either firefox,opera,ie4 or anything else. Conditional compilation relies on annotation labels similar to those used in conditional comments to ensure that it works smoothly in all browsers.

When using conditional compilation, it is best to activate it through the @cc_on statement so that you can include the annotation tag in your script to ensure that the browser is compatible, as shown in the previous example. (Zi Wu Note: This sentence English I translate is not very smooth ... It seems to contradict the above sentence)

@if, @elif, @else, @end statement

After this strange opening, here are some conditional statements for easy conditions:

@if
@elif
@else
@end

Now let's look at some "odd" examples.

If else logic (excluding IE browsers)

/* @cc_on
@if (@_win32)
document.write (The operating system is 32-bit Windows. The browser is IE. ");
@else
document.write (the operating system is not 32-bit Windows.) The browser is IE. ");
@end
@*/

This is a complete script that is identified by IE and ignores all other browsers, and this script displays different content on different operating systems. Compare the following example ...

If Else logic 2 (contains other browsers)

/* @cc_on
/ * @if (@_win32)
document.write (The operating system is 32-bit Windows. The browser is IE. ");
@else @*/
document.write ("Browser is not IE (for example, Firefox) or browser is not in 32-bit Windows under IE." ");
/ * @end
@*/

Skilled use of annotation tags, the else part of this example can include all non-IE browsers (such as Firefox), and not 32-bit Windows under the IE. Work on this note until your head is dizzy and you'll understand the logic.

If, ElseIf, else logic (excluding IE browsers)

Go on, you can see the whole story:

/* @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 2 (contains other browsers)

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

Comprehensive treatment. In this last example, the last else statement contains all non-IE browsers.

Conditional Compilation variables

In the previous section you saw some strange variables like @_win32. Here are some predefined conditional compilation variables that you can use to determine IE or the approximate description of a computer:

In most cases, you may only need to use @_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 in the conditional compilation block, and the syntax is as follows:

@set @varname = term

In conditional compilation, a variable of numeric (Numeric) and Boolean (Boolean) types can be used, but a character type (String) cannot be used. Like what:

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

The standard operators can be used in conditional compilation logic:

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

You can determine whether a user-defined variable is defined by determining whether to return Nan.

@if (@newVar!= @newVar)
The variable is not defined

Because Nan is the only value that is not equal to itself, this script works correctly.

Conditional compilation Example--try catch statement

At the beginning of the tutorial, I used to mention how conditional compilation shows its worth boasting in the presence of some Ajax JavaScript. Now I'm going to tell you what I mean. An AJAX script typically contains a central function to determine the support of browsers (ie, FF, etc.) for generating asynchronous request objects:

Typical Ajax functions:

Function HttpRequest (URL, parameters) {
var pagerequest = False//variable to hold Ajax object
   if (wi Ndow. 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
}

Many people think that Try/catch statements can successfully test AJAX support, unfortunately, this is not true. Browsers that do not support throw/catch, such as IE 4.x, actually block the code above and return an error. To overcome this problem, conditional compilation can be used to reduce a truly cross-browser friendly Ajax processing function:

True Cross-browser functions:

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 complete Try/catch block is only for ie5+, and the rest of the browsers, such as IE4 or non-ie browsers, try to decipher it (dicipher it ...). What is this dicipher? "Deciphering" This explanation is Google to, personal feeling translates to "ignore" seems better? )。 The obvious Firefox will continue and use XMLHttpRequest instead. And now you've got it--a really cross-browser ajax function! (Sub-note: In another article I translate, you can see this function in a more comprehensive way.) )



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.