TJ VanToll

Detecting Internet Explorer without jQuery

| Comments

One of the changes in jQuery’s upcoming 1.9 release is the removal of $.browser. So if you’re using it to test for Internet Explorer, what do you do?

Option 1: Use the migrate plugin

If you want to avoid upgrading existing code, use the migrate plugin which will preserve $.browser as it was. Of course this is simply putting off the inevitable, but if you need to upgrade a large code base it’s a good temporary measure. The development version of the plugin will produce a console warning message whenever $.browser is used, which can help you identify where you’re using it and migrate accordingly.

Option 2: Switch to feature detection

Testing for specific browsers is a bad practice. If you are not supporting IE because of features that it does not possess, test for those features instead of the browser. The Modernizr library includes a wide variety of feature tests and is a good place to get started.

Option 3: Use conditional classes or conditional comments

IE versions < 10 support conditional comments that can be used to detect Internet Explorer. For example the HTML5 boilerplate uses the following to show a warning to users using IE < 7:

<!--[if lt IE 7]>
    <p class="chromeframe">
        You are using an <strong>outdated</strong> browser. Please
        <a href="">upgrade your browser</a>
        or <a href="">
        activate Google Chrome Frame</a> to improve your experience.

This approach can be used to add conditional classes on the html element (via Paul Irish).

<!--[if lt IE 7]>      <html class="ie6"> <![endif]-->
<!--[if IE 7]>         <html class="ie7"> <![endif]-->
<!--[if IE 8]>         <html class="ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html>         <!--<![endif]-->

Now the presence of a class on the html element can be used to derive the version of Internet Explorer the user is using:

$('html').hasClass('ie6'); //True if the user is using IE6

Option 4: Sniff the User Agent

If for whatever reason you cannot do any of the options above, you can determine IE usage the from navigator object.

User agent sniffing should be used as a last resort. Make sure you at least consider the options above before using this.
//Test for Internet Explorer
if (/MSIE\s([\d.]+)/.test(navigator.userAgent)) {
    //Get the IE version.  This will be 6 for IE6, 7 for IE7, etc...
    version = new Number(RegExp.$1);