JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

13.4.6 Conditional Comments in Internet Explorer

Note that client sniffing can be done on the server side as well, with the web server choosing what JavaScript code to send based on how the browser identifies itself in its User-Agent header.


13.4.6 Conditional Comments in Internet Explorer

In practice, you’ll find that many of the incompatibilities in client-side JavaScript programming turn out to be IE-specific. That is, you must write code in one way for IE and in another way for all other browsers. IE supports conditional comments (introduced in IE5) that are completely nonstandard but can be quite useful for working around incompatibilities.

Here is what IE’s conditional comments look like in HTML. Notice the tricks played with the closing delimiter of HTML comments:

This is normal content, displayed by all browsers.

As a concrete example, consider the excanvas.js library described above to implement theelement in Internet Explorer. Since this library is required only in IE (and works only in IE), it is reasonable to include it on your pages within a conditional comment so that other browsers never load it:

Conditional comments are also supported by IE’s JavaScript interpreter, and C and C++ programmers may find them similar to the #ifdef/#endif functionality of the C preprocessor. A JavaScript conditional comment in IE begins with the text /*@cc_on and ends with the text @*/. (The cc in cc_on stands for conditional compilation.) The following conditional comment includes code that is executed only in IE:

/*@cc_on

@if (@_jscript)

// This code is inside a JS comment but is executed in IE.

alert("In IE");

@end

@*/

Inside a conditional comment, the keywords @if, @else, and @end delimit the code that is to be conditionally executed by IE’s JavaScript interpreter. Most of the time, you need only the simple conditional shown above: @if (@_jscript). JScript is Microsoft’s name for its JavaScript interpreter, and the @_jscript variable is always true in IE.

With clever interleaving of conditional comments and regular JavaScript comments, you can set up one block of code to run in IE and a different block to run in all other browsers:

/*@cc_on @if (@_jscript)

13.4 Compatibility and Interoperability | 331

// This code is inside a conditional comment, which is also a

// regular JavaScript comment. IE runs it but other browsers ignore it.

alert('You are using Internet Explorer);

@else*/

// This code is no longer inside a JavaScript comment, but is still

// inside the IE conditional comment. This means that all browsers

// except IE will run this code.

alert('You are not using Internet Explorer');

/*@end

@*/

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31415.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1