Why is Feature Detection needed. Can't we just detect the browser and write code for it?
No, very quickly your list of what each browser does gets out of date, and it will by its very nature be incomplete. (Does the blackberry browser from three years ago support placeholder text in inputs? I have no idea, nor do I need to care.) For example, it used to be that IE didn't have addEventListener
. Now it does. If you start detecting all the way down to the browser version level, then what do you do when new versions come out? It's a maintenance nightmare.
Different ways to do feature detection. Best of them all?
There is no single feature detection, it depends on the feature. You can find a great list of feature detections on this page. There are also libraries like Modernizr that will do the feature-detection for you.
Can you give me a practical real world example where Feature Detection works. How do we handle old browsers and how to replicate the same feature in them>
Sure. I gave you two above, let's dig into them a bit (in reverse order).
addEventListener
: This is a common thing to see in code that doesn't use a library like jQuery, YUI, and the like:
if (elm.addEventListener) {
// Standard
elm.addEventListener("click", myClickHandler, false);
}
else if (elm.attachEvent) {
// IE fallback
elm.attachEvent("onclick", myClickHandler);
}
The great thing about the code above is that when IE9 came out and had addEventListener
(in standards mode), code just worked. No need to update a database to say "IE9 has it now."
Or there's placeholder text in input fields, e.g.:
<input type="text" name="firstName" placeholder="First name">
When browsers don't support the placeholder text, they don't have the placeholder
property on elements; when they do, they do. So this feature-detects whether the browser supports placeholders:
if ('placeholder' in document.createElement('input')) {
// Supports the placeholders
}
else {
// Doesn't, need to do something
}
If it doesn't, you might hook up code to do it yourself. I do that in my place5 plug-in, which is a polyfill for this functionality.