Tiny Javascript to detect versions of Internet Explorer
Here's a nifty little piece of Javascript code that reliably detects the presence of Microsoft's Internet Explorer browser with absolutely minimal processing overhead for all other browsers:
var is_ie/*@cc_on = {
// quirksmode : (document.compatMode=="BackCompat"),
version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])
}@*/;
(Uncomment the second line if you also wish to check whether IE is running in "compatibility" (quirks) mode or in standards-mode.)
The check relies on Microsoft's proprietary conditional compilation syntax, to make sure the object assignment and version number parsing is only performed by Microsoft's browsers.
All other browsers cheerfully ignore the Javascript comment block (/* ... */
) so what they end up with is essentially this:
var is_ie;
...which evaluates as an implicit false
, when used as a condition. This allows us to set up conditions like this one:
if (is_ie && (is_ie.version < 7))
{
// do IE specific stuff
}
else
{
// default behavior for other browsers
}
I lifted the basic idea from Javascript God, Dean Edwards, and extended it to include the version number - which is tremendously useful when dealing with IE's quirky behavior.
Nýleg svör frá lesendum