January 8, 2009 10:59 am GMT

The best method to check for Internet Explorer in Javascript

by Gary Illyes


If you will code in Javascript, or if you already familiarized yourself with it, you encounter many times problems related to the fact that Internet Explorer doesn’t understand a lot of functions which the other browsers can. But the browser market-share dictates that we still have to code in the way to make the script work on Internet Explorer, too.

This meant, many invented small, or relatively small functions to detect the user’s browser. Many times the function is a dozen of lines long, and it’s called every time the script needs to know whether the user’s browser is Internet Explorer or other modern browser.

But there’s a way better way. Better said the simplest way possible. Here it is:

var IE = /*@cc_on!@*/false;

I guess that needs a bit of explanation, right?
What we see up there? I declared a new variable, called IE, which has the value a comment block followed by ‘false‘.
The above variable will be understood by IE: var IE = !false, because Internet Explorer uses JScript — a Javascript-like dialect of the standard ECMAScript — instead of Javascript which is used by all the other browsers. JScript can parse the comments, just like Internet Explorer (see conditional HTML comments post). This is a unique feature of IE, none of the other browsers can do it, so Firefox, Chrome, Safari, Opera, all will understand the above declaration as IE = false.

How to use this in your codes? Put the above code in the first line of your script, then when you need to know whether the browser is Internet Explorer or not, use conditions, like this:

if(IE){
//IE specific code goes here
}else{
//code for all the other browsers
}

Hope this helps you as it helped me many times.


Comments

5 Comments on " The best method to check for Internet Explorer in Javascript "

  1. Kishore on Sun, 3rd May 2009 4:21 am  

    Thanks a lot.
    It works well.

  2. Ross on Tue, 7th Jul 2009 12:31 am  

    Nice, but i’d never remember that one ;-)

  3. pedro on Thu, 17th Sep 2009 1:26 pm  

    Wow.. Thanks alot!

  4. ray on Tue, 22nd Dec 2009 5:31 am  

    works in internet explorer 6.

    your are one reducer of a reducer!

  5. leppidja on Mon, 12th Apr 2010 11:03 am  

    your a genius.
    It’s work very well

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

If you want to use your OpenID, fill out the field labeled "Website" with the OpenID URL. The other fields may remain empty.
Note that comments are pre-moderated.

Subscribe without commenting