Условные комментарии
Best way to check for IE less than 9 in JavaScript without library
What would be your fastest, shortest (best) way to detect browser which is IE and version less than 9 in JavaScript, without using jQuery or any add-on libraries?
I’m fully aware of conditionals in the DOM. Only interested in a small best performing JavaScript solution.
Don’t forget that feature detection is the most reliable thing when you want to use a version-specific feature (However, the feature can exist but be buggy in some version, keep this in mind). If you want to display browser version on the page, use browser detection.
I agree Dan, but in truth, it’s often not straight-forward and/or easy for everyone to tie a particular difference to a feature (detection). Even if it is, the code may be easier to read when it is like the answer provided (example: ie < 9).
14 Answers 14
var ie = (function() < var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = 'Читайте также: Python with django tutorial
That’s the best answer in my opinion, browser detection should be approached by detecting specific functions/
I like this answer. It’s not browser version detection, it’s browser capability detection — which is usually more useful. Detecting a feature like ‘addEventListener’ will not only separate IE8 from IE9, it will separate old browsers from HTML5 capable browsers in general.
Unfortunately, this fails if you’ve polyfilled document.addEventListener . IE conditional comments are failproof in that regard.
Using conditional comments, you can create a script block that will only get executed in IE less than 9.
Of course, you could precede this block with a universal block that declares var is_ie_lt9=false , which this would override for IE less than 9. (In that case, you’d want to remove the var declaration, as it would be repetitive).
EDIT: Here’s a version that doesn’t rely on in-line script blocks (can be run from an external file), but doesn’t use user agent sniffing:
with(document.createElement("b"))1",innerHTML>0);var ie=id>5?+id:0>
It has the advantage of not involving any RegEx and, presumably, not being spoofable. IE parses the variable like its nothing. (Which, for IE, is saying something.)
this is pretty good, I could use if(window.ielt9). I wonder if there could there be a non-inline script solution that is better than this? (which would be posh. )
It seems like @cwolves’s solution would allow you to run it in an external script (I’ve never tried it.)
bah to conditional comments! Conditional code all the way. (silly IE)
Seriously though, just throwing this out there in case it suits you better. they're the same thing, this can just be in a .js file instead of inline HTML
Note: it is entirely coincidental that the jscript_version check is "9" here. Setting it to 8, 7, etc will NOT check "is IE8", you'd need to lookup the jscript versions for those browsers.
@bcm - you should get IE_LT_9 == false in IE9 and true in IE8. I'm using a mac right now and don't have a PC here, so I can't test it, but I pulled that out of code I wrote that I know works. If it's not working for some reason, alert(@_jscript_version) to see what you get and adjust from there.
sigh the code works, IE9 doesn't actually run IE7 when it's in 'compatibility mode', it still uses IE9's JS engine. jsfiddle.net/aNGXS According to IETester: IE9 says `9', IE8 says '5.6'
either way, use a stand-alone version of IE8 and you WILL NOT get '9' in that alert. You'll get '5.8' or something similar (not sure specifically if they ever updated the JScript engine, but it's NOT 9)
OMFG, I just tested this on FIVE machines via RDC and it works on EVERY one. IE8 says '5.8', IE9 says '9'. You're doing something wrong or assuming that you're not using the IE9 engine when you are. As I said, IE9 in "compatibility mode" or with a different user agent is still IE9. Run a stand-alone version of IE8, IE7 or anything previous and the code works.
You're still running IE9 though! This detects -THAT-. If you run a standalone copy if IE8, it'll show that. Don't blame me for Microsoft dev tools being worthless.
Below is an improvement over James Padolsey's solution:
1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.
/* - Behavior: For IE8+, we detect the documentMode value provided by Microsoft. - Behavior: For else < for (var i = 7; i >0; i--) < var div = document.createElement("div"); div.innerHTML = " Для всех браузеров кроме IE
В первой и третьей строке добавляется --> , браузеры воспринимают эти строки как комментарий и игнорируют. Internet Explorer в свою очередь считает их условными комментариями и обрабатывает согласно своей логике.
Условные комментарии это главное средство для исправления ошибок Internet Explorer. Простой и понятный синтаксис делает ненужными всяческие хаки, заменяя их стандартной конструкцией. Стили для IE правильнее выделить в отдельный CSS-файл, который будет загружаться только при необходимости.
Для всех браузеров подключается файл style.css, а для IE версии 7.0 и ниже ещё один файл ie.css. При этом остальные браузеры этот файл будут игнорировать и не загружают.
Статьи по теме
Источник