在没有库的 JavaScript 中检查 IE 是否小于 9 的最佳方法

发布于 2024-10-31 01:26:11 字数 79 浏览 5 评论 0原文

在不使用 jQuery 或任何附加库的情况下,检测 IE 浏览器和 JavaScript 版本低于 9 的浏览器的最快、最短(最佳)方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

弄潮 2024-11-07 01:26:12

使用条件注释,您可以创建一个仅在小于 9 的 IE 中执行的脚本块。

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]--> 

当然,您可以在此块之前添加一个声明 var is_ie_lt9=false 的通用块,这将对于小于 9 的 IE 进行覆盖。(在这种情况下,您需要删除 var 声明,因为它会重复)。

编辑:这是一个不依赖于内联脚本块(可以从外部文件运行)的版本,但不使用用户代理嗅探:

通过 @cowboy

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}

Using conditional comments, you can create a script block that will only get executed in IE less than 9.

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]--> 

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:

Via @cowboy:

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}
ゝ偶尔ゞ 2024-11-07 01:26:12

有条件评论啊!一路有条件代码!!! (愚蠢的 IE)

<script type="text/javascript">
/*@cc_on
   var IE_LT_9 = (@_jscript_version < 9);
@*/
</script>

不过说真的,只是把它扔在那里以防万一它更适合你......它们是同一件事,这可以只是在 .js 文件中而不是内联 HTML

注意: jscript_version 完全巧合此处检查为“9”。将其设置为 8、7 等不会检查“is IE8”,您需要查找这些浏览器的 jscript 版本。

bah to conditional comments! Conditional code all the way!!! (silly IE)

<script type="text/javascript">
/*@cc_on
   var IE_LT_9 = (@_jscript_version < 9);
@*/
</script>

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.

喜爱纠缠 2024-11-07 01:26:12

下面是对 James Padolsey 解决方案的改进:

1) 它不会污染内存(例如,James 的代码片段在检测 IE11 时会创建 7 个未删除的文档片段)。
2) 速度更快,因为它在生成标记之前检查 documentMode 值。
3) 它更加清晰易读,尤其是对于 JavaScript 初学者来说。

要点链接:https://gist.github.com/julianshapiro/9098609

/*
 - Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
 - Behavior: For <IE8, we inject conditional comments until we detect a match.
 - Results: In IE, the version is returned. In other browsers, false is returned.
 - Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/

var IE = (function() { 
    if (document.documentMode) {
        return document.documentMode;
    } else {
        for (var i = 7; i > 0; i--) {
            var div = document.createElement("div");

            div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";

            if (div.getElementsByTagName("span").length) {
                return i;
            }
        }
    }

    return undefined;
})();

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.

Gist link: https://gist.github.com/julianshapiro/9098609

/*
 - Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
 - Behavior: For <IE8, we inject conditional comments until we detect a match.
 - Results: In IE, the version is returned. In other browsers, false is returned.
 - Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/

var IE = (function() { 
    if (document.documentMode) {
        return document.documentMode;
    } else {
        for (var i = 7; i > 0; i--) {
            var div = document.createElement("div");

            div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";

            if (div.getElementsByTagName("span").length) {
                return i;
            }
        }
    }

    return undefined;
})();
痕至 2024-11-07 01:26:12
var ie = !-[1,]; // true if IE less than 9

ie5、6、7、8 支持此 hack。它在ie9+中已修复(因此它适合这个问题的要求)。此技巧适用于所有 IE 兼容模式。

工作原理:即引擎将包含空元素的数组(如 [,1])视为包含两个元素的数组,而不是其他浏览器认为只有一个元素。因此,当我们使用 + 运算符将此数组转换为数字时,我们会执行以下操作:(ie 中的 ',1' / 其他中的 '1')*1,我们在 ie 中得到 NaN,在其他中得到 1。然后我们将其转换为布尔值并使用 ! 反转值。简单的。顺便说一句,我们可以使用更短的版本,而不需要!符号,但值将反转。

这是目前最短的 hack。我是作者;)

var ie = !-[1,]; // true if IE less than 9

This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.

How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.

This is the shortest hack by now. And I am the author ;)

棒棒糖 2024-11-07 01:26:12

我决定改用对象检测。

读完这篇文章后:
http://www.quirksmode.org/js/support.html
还有这个:
http://diveintohtml5.ep.io/detect.html#canvas

我会使用类似的东西

if(!!document.createElement('canvas').getContext) alert('what is needed, supported');

I've decided to go with object detection instead.

After reading this:
http://www.quirksmode.org/js/support.html
and this:
http://diveintohtml5.ep.io/detect.html#canvas

I'd use something like

if(!!document.createElement('canvas').getContext) alert('what is needed, supported');
野鹿林 2024-11-07 01:26:12

此链接包含有关检测 Internet Explorer 版本的相关信息:

http://tanalin.com/ en/articles/ie-version-js/

示例:

if (document.all && !document.addEventListener) {
    alert('IE8 or older.');
}

This link contains relevant information on detecting versions of Internet Explorer:

http://tanalin.com/en/articles/ie-version-js/

Example:

if (document.all && !document.addEventListener) {
    alert('IE8 or older.');
}
小糖芽 2024-11-07 01:26:12

您可以使用正则表达式和 .match() 以快速而肮脏的方式完成此操作:

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}
萌酱 2024-11-07 01:26:12

如果我是你,我会使用条件编译或功能检测。
这是另一种选择:

<!--[if lt IE 9]><!-->
<script>
    var LTEIE8 = true;
</script>
<!--<![endif]-->

If I were you I would use conditional compilation or feature detection.
Here's another alternative:

<!--[if lt IE 9]><!-->
<script>
    var LTEIE8 = true;
</script>
<!--<![endif]-->
日裸衫吸 2024-11-07 01:26:12

我喜欢 Mike Lewis 的回答,但代码没有通过 jslint,我无法理解时髦的 while 循环。我的用例是,如果小于或等于 IE8,则显示不支持浏览器的消息。

这是基于 Mike Lewis 的 jslint 免费版本:

/*jslint browser: true */
/*global jQuery */
(function () {
    "use strict";
    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
    }
}());

I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.

Here is a jslint free version based on Mike Lewis':

/*jslint browser: true */
/*global jQuery */
(function () {
    "use strict";
    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
    }
}());
那一片橙海, 2024-11-07 01:26:12

是否需要用 JavaScript 来完成?

如果没有,那么您可以使用 IE 特定的条件注释语法:

<!--[if lt IE 9]><h1>Using IE 8 or lower</h1><![endif]-->

Does it need to be done in JavaScript?

If not then you can use the IE-specific conditional comment syntax:

<!--[if lt IE 9]><h1>Using IE 8 or lower</h1><![endif]-->
耀眼的星火 2024-11-07 01:26:12
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
    // IE8 or less
}
  • 使用以下命令提取 IE 版本: /MSIE\s(\d+)/.exec(navigator.userAgent)
  • 如果它是非 IE 浏览器,则会返回 null 因此在这种情况下 < code>||0 会将 null 切换为 0
  • [1] 将获取 IE 的主要版本或 undefined如果不是IE浏览器
  • 前导+会将其转换为数字,undefined会转换为NaN
  • 比较NaN 带有数字将始终返回 false
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
    // IE8 or less
}
  • extract IE version with: /MSIE\s(\d+)/.exec(navigator.userAgent)
  • if it's non-IE browser this will return null so in that case ||0 will switch that null to 0
  • [1] will get major version of IE or undefined if it was not an IE browser
  • leading + will convert it into a number, undefined will be converted to NaN
  • comparing NaN with a number will always return false
暗恋未遂 2024-11-07 01:26:12

你们都试图把这么简单的事情复杂化。只需使用简单明了的 JScript 条件注释即可。它是最快的,因为它向非 IE 浏览器添加了零代码进行检测,并且它的兼容性可以追溯到支持 HTML 条件注释之前的 IE 版本。简而言之,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

谨防缩小器:大多数(如果不是全部)会将特殊条件注释误认为是常规注释,并将其删除

基本上,上面的代码将 IE_version 的值设置为您的 IE 版本正在使用,如果您没有使用 IE,则为 -1。现场演示:

var IE_version=(-1/*@cc_on,@_jscript_version@*/);
if (IE_version!==-1){
    document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
} else {
    document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");
}

You are all trying to overcomplicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it

Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:

var IE_version=(-1/*@cc_on,@_jscript_version@*/);
if (IE_version!==-1){
    document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
} else {
    document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");
}

苄①跕圉湢 2024-11-07 01:26:11

Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

然后您可以执行以下操作:

ie < 9

作者:James Panolsey,来自此处:http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

You can then do:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

阪姬 2024-11-07 01:26:11

物有所值:

    if(  document.addEventListener  ){
        alert("you got IE9 or greater");
    }

这成功地针对 IE 9+,因为除 IE 之外的所有主要浏览器很早就支持 addEventListener 方法。 (Chrome、Firefox、Opera 和 Safari)MDN 参考。目前 IE9 支持它,我们预计今后将继续支持它。

for what it's worth:

    if(  document.addEventListener  ){
        alert("you got IE9 or greater");
    }

This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文