JavaScript

Please don't detect the browser

Feature detection is a term everyone in the web development world has heard of. Yet, we still find code that tries to detect which browser the user is running to perform a task. This needs to stop! Technology has evolved to the point we don't need browser detection tricks anymore.

Why do you think there isn't a Windows 9? It's because people thought it would be cool to check which operating system their application was running on, and based on that they would run specific code. Now we have code like this that breaks compatibility:

if (version.StartWith("Windows 9"))
{
    // do windows 95 or 98 stuff
}

If the next version of windows was 9 than it would be a nightmare to maintain backward compatibility with a plethora of applications.

Checking which browser is running might break future compatibility for your application. The moment someone changes the browser User Agent your code might break. Long ago, I read of a small hack to determine if a browser is IE, even if the user spoofs the user agent:

var IE = (!+"\v1")?true:false; // true only in IE

This worked great, until one day it didn't. I was lucky I wasn't using this trick to run IE specific code. Instead I was just trying to log how many users where using IE. When IE 9 came out, this same statement, would return false. If I was doing IE centric things like using attachEvent based on the browser, my code would fail.

if (IE){
    element.attacheEvent("onclick",fn);
}else {
    element.addEventListener("click",fn);
}

The moment the user upgrades to IE 9, the code breaks. The lesson here is don't check which browser is running to do a task. Instead check if the feature you are trying to use is supported first.

if (element.attachEvent){
    element.attacheEvent("onclick",fn);
}else {
    element.addEventListener("click",fn);
}

In the ideal world, you would write code once and it will work everywhere. But we don't live in such world, so make sure to support features not browsers and your application may just pass the test of time.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only