I want to sniff the current version of IE8 (and I'm so sorry, but no other way, I have to do that). I know that feature sniffing should be used instead of browser sniffing, but hey, my boss doesn't know that, right?
Now I used this conditional compiling code:
var ie8 = false/*@cc_on @_jscript_version == 8@*/
开发者_高级运维
But seems that it also includes IE7. Any idea?
Without using conditional compiles, you could use conditional comments to set a class on the html
element for each IE you want to test for, like:
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->
(from http://initializr.com/)
Then it would be a simple matter of testing for the class in JS:
var ie8 = !!document.getElementsByTagName("html")[0].className.match(/ie8/);
The following presumes you are using Internet Explorer...
Firstly, it is extremely abnormal to test for the browser version - the document.documentMode is what should be tested for (because a page can be in IE8 mode even if using IE9 or IE10):
if (document.documentMode == 8) { ...
If you have some really strange requirement, then you can reliably detect the JScript version e.g. _jscript_version is 5.8 for IE8 (see http://en.wikipedia.org/wiki/Conditional_comment ):
var ieJsVer = Function('return/*@cc_on @_jscript_version @*/;')();
var isIE8 = (ieJsVer == 5.8);
The conditional comment is put inside a string so that it won't be removed by any JavaScript compression that might occur (which may strip out comments).
Important Internet Explorer 11 edit:
- Added ; at end of Function() string - otherwise IE11 in EDGE mode throws an exception - arrrgh!
- IE11 in EDGE mode then ieJsVer is undefined
- IE11 in docMode <= 10 then ieJsVer is 11
- IE11 in EDGE mode returns undefined for document.documentMode
Why not use conditional comments to toggle a script that sets the variable? Like:
<head>
<script>
window.ie8 = false;
</script>
<!--[if IE 8]>
<script>
window.ie8 = true;
</script>
<![endif]-->
</head>
Granted it's a bit verbose, but perhaps it's also more reliable.
精彩评论