Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the means, benefit and differences between User Agent detection and Feature Detection?

What is the means, benefit and differences between User Agent detection and Feature Detection? and which one is better?

And please give usages examples for both.

like image 674
Jitendra Vyas Avatar asked Jan 19 '23 16:01

Jitendra Vyas


2 Answers

The main reason to use feature detection as opposed to user agent sniffing is future proofing.

Let's say, for example, that you want to use some new XMLHttpRequest 2.0 features (just making this up). You know IE doesn't support it but Firefox does, and so you have code like this in your JS:

if (!IE) {
    UseNewAjax();
} else {
    UseOldAjax();
}

Later, a new version of IE comes out which supports the new features, but because you are agent-sniffing, your IE viewers can't get this feature goodness without you making a change to your code.

On the other hand, if you feature detection:

if (document.hasCoolNewAjax) {
    UseNewAjax();
} else {
    UseOldAjax();
}

You can be assured in the future that if a browser supports a feature they didn't before, they can start using these features immediately, and you don't have to change your code to support it.

Browser / User Agent sniffing: Using a programming language to determine what browser a visitor is using, so special logic can be written against that browser. Inefficient and considered a bad practice in the development community.

Feature detection: Using a programming language to determine whether a browser supports a particular feature. Considered a best practice in the developer community because it is fool-proof and future-proof.

From Wikipedia:

User agent sniffing is mostly considered poor practice, since it encourages browser-specific design and penalizes new browsers with unrecognized user agent identifications. Instead, the W3C recommends creating HTML markup that is standard,[citation needed] allowing correct rendering in as many browsers as possible, and to test for specific browser features rather than particular browser versions or brands.

JavaScript isn't the only language which you can user-agent sniff or feature detect from. For example, the .NET framework has properties that let you read all sorts of information about the browser:

http://msdn.microsoft.com/en-us/library/3yekbd5b.aspx

http://modernizr.com

like image 58
Eli Avatar answered Jan 22 '23 05:01

Eli


Feature detection is always better than user agent detection because users can spoof their user agent string, so it's unreliable.

like image 41
onteria_ Avatar answered Jan 22 '23 05:01

onteria_