Javascript IE detection, why not use simple condit

2019-01-03 23:10发布

In order to detect IE most Javascript libaries do all sort of tricks.

  • jQuery seem to add a temporary object into your pages's DOM to detect some features,
  • YUI2 does regex on the user agent in its YAHOO.env.ua = function() (file yahoo.js)

After reading this answer it came in my mind that it's true, in order to detect simply IE in Javascript we could simply add to our pages:

<!--[if IE]><script type="text/javascript">window['isIE'] = true;</script><![endif]-->

<script type="text/javascript" src="all-your-other-scripts-here.js"></script>

Now the window.isIE variable is set for all our Javascript code, by simply doing:

if(window.isIE)
   ...

Beside the fact that this might result in being a pain because it has to be added in all pages, are there any issues/considerations I might be unaware of?


FYI: I know it's better to use object detection rather than browser detection, but there are cases where you still have to use browser detection.

15条回答
姐就是有狂的资本
2楼-- · 2019-01-03 23:55

Why don't you just program in HTML5, and check that

if ( window.navigator.product !== "Gecko" )

?? True, this will include IE11 in the "Gecko" bunch, but isn't it supposed to be good enough now?

Note: the HTML5 spec. says that navigator.product must return "Gecko"... and IE10 and earlier all return something else.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-03 23:57

For my use case, I really just need to detect if lower than IE9, so I use

if (document.body.style.backgroundSize === undefined && navigator.userAgent.indexOf('MSIE') > -1)
{
//IE8- stuff
}
查看更多
在下西门庆
4楼-- · 2019-01-03 23:58

I'm using that code

var isIE = navigator.userAgent.indexOf(' MSIE ') > -1;

查看更多
登录 后发表回答