Why browser detection with JavaScript is a bad habit?

What’s wrong with this JavaScript function?

var xmlHttp = function(){
    var r = null;
    var browser = navigator.appName;
    if(browser == 'Microsoft Internet Explorer'){
        r = new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        r = new XMLHttpRequest();
    };
    return r;
};

You don’t have a clue? Then this is the right article for you… (well except you don’t know why are you reading this in the first place)

Let’s say you run this script in Opera. Opera is by default declaring its’ navigator.appName as Microsoft Internet Explorer (open the W3schools TryIt Editor in your default Opera installation).

In case of Opera, the first condition would match, but the trouble is – Opera doesn’t support ActiveXObject object and it will throw you an error. Furthermore, if a browser is not Microsoft Internet Explorer and it doesn’t support XMLHttpRequest, the browser will also hang.

In the above example the function detects browser version, instead of its’ support for a method at hand. On the other hand, if you test for a method and the browser fails, it will simply skip to a next check. The correct approach for the above example would be:

var xmlHttp = function() {
    var r = null;
    if (window.XMLHttpRequest) {
        r = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        var msp = new Array('Msxml2.XMLHTTP','Microsoft.XMLHTTP');
        for (var i = 0; i < msp.length; i = i + 1) {
            try { r = new ActiveXObject(msp[i]); } catch (e){};
        };
    };
    return r;
};

Right?

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?