Capability detection - the better way

By crisp on Sunday 3 December 2006 23:04
Category: Javascript, Views: 4.567

I read this article today on dev.opera.com about javascript capability detection. They are right that capability detection is a far better way to determine support for certain features than to make assumptions based upon sniffing the user-agent string.

Now my eye caught their example of a classic case:

JavaScript:
1
2
3
4
5
6
7
8
9
10
11
function findElement(id){
    if(document.getElementById){ // standardised method first
        return document.getElementById(id);
    }else if(document.all){
        return document.all[id];
    }else if(document.layers){
        return document.layers[id];
    }else{
        return null;
    }
}



I'd say this is wrong; first of all it means you have to start using a non-standard function and thus a non-standard method of working throughout your code, and secondly the object detection is being done each and every time you call this function.

In my opinion this would be a far better way:

JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (!document.getElementById)
{
    if (document.all)
    {
        document.getElementById = function(id)
        {
            return document.all[id];
        }
    }
    else if (document.layers)
    {
        document.getElementById = function(id)
        {
            return document.layers[id];
        }
    }
    else
    {
        document.getElementById = function(id)
        {
            return null;
        }
    }
}



Now you can use the standard way, using document.getElementById(), throughout your script without having to worry about older browsers. It's a non-obtrusive and efficient way to add modern capabilities to older browsers.

Now this might not be a very good example in itself because IE4 and NS4 are long out of the picture, but this might make a better one:

JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (!window.XMLHttpRequest)
{
    window.XMLHttpRequest = function()
    {
        // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
        var types = [
            'MSXML2.XMLHTTP.6.0',
            'MSXML2.XMLHTTP.3.0'
        ];

        for (var i = 0; i < types.length; i++)
        {
            try
            {
                return new ActiveXObject(types[i]);
            }
            catch(e) {}
        }

        return undefined;
    }
}

Volgende: .toJSONString() and Object.prototype 12-'06 .toJSONString() and Object.prototype
Volgende: Having fun with IE - part 3: doctype switching 12-'06 Having fun with IE - part 3: doctype switching

Comments

Comments are closed