0

guys,

Just upgrade from jQuery 1.8.3 to 1.11, the browser object is removed from 1.9 and judgement with user-agent is not recommended. But I still need to detect if browser is IE or not at a certain point of my code.

The conditional stylesheet is only supported from IE6-IE9, I search and search and it seems only user-agent is the ultimate way.

Is there a way to do that? Which could detect the browser is IE, not using user-agent and work from IE8 to IE11?

Thanks a lot.

larryzhao
  • 3,173
  • 2
  • 40
  • 62
  • 1
    It's less user-agent which is not recommended than the whole browser detection logic. If you really need to detect the browser, use user-agent. But you probably **don't** need to detect if the browser is IE, more probably you need to detect if a specific feature is available. – Denys Séguret Apr 22 '14 at 10:06
  • How to Detect Features Instead of Browsers http://msdn.microsoft.com/en-us/library/hh273397%28v=vs.85%29.aspx – Paul Apr 22 '14 at 10:10
  • Here you can use this answer to detect IE http://stackoverflow.com/questions/18145816/execute-certain-javascript-if-browser-lt-ie9 – Sandeeproop Apr 22 '14 at 10:12

2 Answers2

1

The most reliable way for IE 5-9 is using conditional comments:

var div = document.createElement("div"), ie;
div.innerHTML = "<!--[if IE 5]>5<![endif]--><!--[if IE 5.0]>5<![endif]-->"
        + "<!--[if IE 5.5]>5.5<![endif]--><!--[if IE 6]>6<![endif]-->"
        + "<!--[if IE 7]>7<![endif]--><!--[if IE 8]>8<![endif]-->"
        + "<!--[if IE 9]>9<![endif]-->";
if (div.firstChild && div.firstChild.nodeType === 3) ie = +div.innerHTML;

But this doesn't work for IE10-11, as those don't support conditional comments, and IE11 not even when in compatibility mode (and that kind of sucks - conditional comments have been used a lot). Edit: fortunately, that has been fixed the exact same day I gave this answer. Ah!

You can still check if it's IE10-11 if you manage to detect its vendor prefix, for example:

var prop, isIE = false;
for (prop in div.style)
    if (/^ms[A-Z]/.test(prop)) {
        isIE = true;
        break;
    }

This works but you won't be able to tell IE10 from IE11, unless you check the UA string or some recent features.

But honestly, IE10+ is fine, and should also get automatic updates. You should go for feature detection for those, and forget about the version.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
0

There are at least two solutions to solve your problem:

  1. Detect browser features (recommended) Dokumentation for modernizr here
  2. Use jQuery Migrate Plugin Download here

Modernizr aims to bring an end to the UA sniffing practice. Using feature detection is a more reliable mechanic to establish what you can and cannot do in the current browser - Taken from modernizr.com

Pascal Bayer
  • 2,615
  • 8
  • 33
  • 51