IE Detection in JavaScript

coney Island Beach, New York
Creative Commons License photo credit: Ben30

Here is another useful piece on JavaScript I’d like to share with you. Every now and then I need to execute a part of JavaScript code depending on the browser.

If those parts of code are completely different functionalities then I’m going with conditional comments and different script files for different browsers. If those are different ways of getting an object (like getting height of the client window) I’m going with ternary operator ?:. Big question is: what do you do in between those cases?

Sometimes you just need to change execution of few lines depending on user’s browser. What do you do? You check if the code is being executed on the particular browser and apply changes. And how exactly it is done?

In most parts you need to be able to determine if site is being browsed on Internet Explorer or not. In more detailed cases you will need to determine whether it is an IE6 or IE7. How do you do it?

Conditional compilation of JavaScript.

Sounds scary doesn’t it? Well it is an IE only thing so do not worry. Basically it allows you to add (for IE only) some conditions determining behavior and execution of your JavaScript code. All in all it is a great tool to use if you want to determine IE version. How do you do it? Simple. Look here:

To check if JavaScript is being executed in IE this little snippet helps:
var isIE = /*@cc_on!@*/false;
this isIE variable is false in any browser other than IE

To check if JavaScript is being executed in IE6 use this:
var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
isIE6 variable is true only in Internet Explorer and only in IE6 - just what we need.

To check if JavaScript is being executed in IE7 use this:
var isIE7 = false /*@cc_on || @_jscript_version >= 5.7 @*/;
isIE7 will be true only in IE7 now.

Alternative methods base on implementation of methods of common objects like “window” or “document”. This approach is quite popular and almost always enough but I can imagine situations where someone adds the missing implementations to JavaScript objects (for fun or to fix an issue) and then the check will fail.

Method that I proposed is based only on the version of JavaScript implemented in particular browser and that won’t change.

I hope this little snippet did help anybody. I’ve recently used it in a project and that in the end (many changes later) saved me quite some time.

Share this post: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • StumbleUpon
  • Technorati
  • Reddit
  • Slashdot
  • del.icio.us
  • Wykop

About this entry