Reputation: 20106
I've seen this method of detecting IE in several online examples:
if (/*@cc_on!@*/false) { // check for Internet Explorer
Is this similar to the conditional comments IE recognizes in HTML?
Upvotes: 2
Views: 2222
Reputation: 34117
We have a good description here
Conditional compilation.
This method is THE method of choice right now. Dean Edwards described this gem of an approach on his blog post Sniff. As far as I can tell, it is the cleanest and most reliable way to detect IE.
var isMSIE = /*@cc_on!@*/false;
Simple, isn’t it? No User-Agents, no 20 lines of conditional statements and string searches.
How does this code work? Internet Explorer uses JScript, a proprietary form of JavaScript (ECMAScript) developed by Microsoft. JScript has a feature called conditional compilation, which allows us to add JScript-specific JavaScript inside a specially formatted comment. Other JavaScript compilers will ignore this code, thinking it’s a comment, while JScript will recognize it and process it.
/*@cc_on begins the comment, and @*/ ends the comment.
When any non-IE browser sees var isMSIE = /*@cc_on!@*/false;, it actually sees it as var isMSIE = false;. Internet Explorer’s JScript will add the exclamation point contained in the comment, meaning IE will see var isMSIE = !false;. Remember, an exclamation point reverses a boolean’s value, so !false is equivalent to true.
As Dean pointed out, there is an even simpler way to write this (though it’s slightly less legible):
var isMSIE/*@cc_on=1@*/;
If a variable is not assigned a value when it is declared, by default it will return ‘falsy‘ (null). Thus a non-IE browser will see this line as var isMSIE; while Internet Explorer’s JScript will see it as var isMSIE=1; (assigning a 1 makes the variable ‘truthy‘).
I prefer to shorten it a bit more by removing the MS from isMSIE, making it simply isIE. Note: it’s a best practice to give booleans a name that implies what the boolean stands for, usually in a quasi-question format. Using plain old var IE doesn’t tell us the variable is a boolean, and doesn’t tell us what question is being answered by the boolean’s value. var isIE does.
var isIE/*@cc_on=1@*/;
if(isIE){
//Do something. I suggest downloading Firefox. ^_^
}
Upvotes: 2
Reputation: 437386
This statement controls conditional compilation of comment contents in IE. If IE sees this comment, it actually compiles the contents of comment blocks as pure code. Now the trick happens with the !
in the comment.
IE compiles the !
as if it were written into source so it handles the code as if (!false)
, while all other browsers treat it as if (false)
.
Upvotes: 3
Reputation: 1760
Microsoft offers some helpful insight into this.
It seems as though this declaration tells the script whether or not the browser will support conditional compilation, and if so, then execute any code following that would be enclosed in
/*@ ...
... @*/
Upvotes: 1