Wednesday, December 27, 2006

Javascript: Conditional Comments and Conditional Compilation

Recently came across some cool new features of Javascript that reduced the amount of coding required. For many years, developers have been writing Javascript code to detect the browser type and accordingly fire javascript functions or do a document.write()

But now there are more developer-friendly ways of detecting the browser type and handling content.
Conditional Comments: These look like HTML comments, but IE browsers treat them differently.
For e.g.
<!--[if IE]>You are using IE (IE5+ and above).<![endif]-->
The above line would be rendered only if the browser is IE.

To render something if the browser in non-IE use the following:
<![if !IE]>You are NOT using IE.<![endif]>

We can also check the IE version number:
<!--[if IE 6]>You are using IE 6!<![endif]-->

Another feature of IE is Conditional Compilation. Non-IE browsers would ignore the @cc block
/*@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.");

No comments:

Post a Comment