Object detection and browser sniffing: ongoing confusion
Browsers are not created equal. As client-side developers, we are more than often confronted with faulty implementations and missing features which force us to write specific code for the browsers we wish to support.
But writing specific code for a browser implies that you can differentiate it from others from within your own code. There are mainly two techniques to achieve this: object detection and browser sniffing. In the manichean world of javascripters, one is good (the former) the other is bad (the latter). Let's briefly have a look at both of them before we pursue:
Object detection
Object detection is pretty simple: before using a method or function, just check to see if it is supported by the current browser.
if(document.getElementById) document.getElementById('my-div');
else alert('Your browser sucks, please update it!'):
Unfortunately, sometimes a function or method exists but does not work, or has been implemented incorrectly. In which case, browser sniffing is often the only option available.
Browser sniffing
Browser sniffing relies on identifying the browser (usually by parsing information specifically provided by it's vendor) so as to provide it with specific code that is known to work for it.
For example:
if (/MSIE\s6/).test(navigator.appVersion) {
// specific code for IE6
}
There are however many issues with this technique:
- It is difficult to account for all existing browsers,
- historically, some minor browsers have been known to disguise as Internet Explorer despite not having the same feature-set,
- scripts have to be updated with every new release, etc.
which is why browser sniffing has always been tagged as bad.
Where confusion arises
Because of browser sniffing's caveats (and more often just because of its filthy reputation), competent coders rightfully favor object detection whenever possible. This goes to such an extent that even when object detection just cannot be used, some zealous coders will mimic it, sometimes firmly believing they are using object detection, while all what they are doing is mere browser sniffing.
if(document.all && !window.opera) { // targets Internet Explorer
document.getElementById('my-div').style.filter = 'alpha(opacity=50)';
}
Although the above can look like object detection, (we are detecting the presence of the all and opera properties), it is not! True object detection implies testing for the existence of a property or method you are planning to use, not that you know exists only in a certain browser. Think about it: what happens if suddenly Safari (or any other browser) decides to implement a document.all property but does not implement opacity the way Internet Explorer does?