Detecting IE version directly on Javascript
Hello all, it’s been a while, projects and vacations were imminent so I’ve got few time for writing any article.
Anyway today we’ll speak about something simple but useful, suppose we’re dealing with JS animations but we already know that IE older versions could have trouble and we want to resolve this catching the browser version and putting different code for IE.
Many would probably do a common conditional like this:
<!--[if lt IE 8]>
<script>
do_awesome_stuffs();
</script>
<![endif]-->
which is probably the best solution overall. However since we are dealing with a JS animation we’ll probably prefer to address to the fix directly in the animation function code, so how to detect IE version directly in JS?
The code (source) can be similar to this:
function IE(v) {
var r = RegExp('msie' + (!isNaN(v) ? ('\\s' + v) : ''), 'i');
return r.test(navigator.userAgent);
}
if(IE()) { alert('Internet Explorer!'); }
if(IE(10)) { alert('Internet Explorer 10!'); }
/* Thanks to Daryl Ginn */
It works flawlessly and it’s elegant.
EDIT: Since IE11 came out, we need something different, just as suggestion a general IE detector here:
function IE() {
var rv = false;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null){
rv = parseFloat( RegExp.$1 );
}
}
else if (navigator.appName == 'Netscape')
{
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null){
rv = parseFloat( RegExp.$1 );
}
return rv;
}
That’s all!
No comments yet.