Don't over complicate 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@*/);_x000D_
if (IE_version!==-1){_x000D_
document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");_x000D_
} else {_x000D_
document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");_x000D_
}
_x000D_
This works based on the fact that conditional comments are only visible in older versions of Internet Explorer, and IE sets @_jscript_version
to the version of the browser. For example, if you are using Internet Explorer 7, then @_jscript_version
will be set to 7
, thus, the postprocessed javascript that will be executed will actually look like this:
var IE_version=(-1,7);
which gets evaluated to 7.