Saturday, November 24, 2007

Easiest way to check IE version with JavaScript

Alright, so I needed a easy way to execute custom JavaScript for clients using versions of IE lower than 7. All the scripts Google showed me were really huge and quite outdated. So I took what I found, and turned it into something really lightweight. Note that this is just a quick hack, but so far it seems to be enough for my needs.

Code:


var Browser = {
Version: function() {
var version = 999; // we assume a sane browser
if (navigator.appVersion.indexOf("MSIE") != -1)
// bah, IE again, lets downgrade version number
version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}


Which enables me to do stuff like this:


if (Browser.Version() < 7) {
... // if client is using IE6 or lower, run this code
}


..or this:


if (Browser.Version() >= 7) {
... // if client is using IE7 or a sane browser, run this code
}


It will simply return 999 if the browser is non-IE. Is it safe to assume that navigator.appVersion always will contain "MSIE" in uppercase?

3 comments:

zamkinos said...

thanks...

Anonymous said...

Thanks alot man! Worked good!

Anonymous said...

doesn't work for IE 8, I get version 7 as result