I was asked this question in a job interview recently, specifically around Javascript. I was wondering the proper response.
What exactly is the difference between feature detection
, feature inference
, and using the User agent
string?
I was asked this question in a job interview recently, specifically around Javascript. I was wondering the proper response.
What exactly is the difference between feature detection
, feature inference
, and using the User agent
string?
Feature detection checks a feature for existence, e.g.:
if (window.XMLHttpRequest) {
new XMLHttpRequest();
}
Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:
if (document.getElementsByTagName) {
element = document.getElementById(id);
}
Checking the UA string is an old practice and should not be used anymore. You keep changing the UA checks and never benefit from newly implemented features, e.g.:
if (navigator.userAgent.indexOf("MSIE 7") > -1){
//do something
}
Feature detection: actually checking that the feature exists
if('localStorage' in window)
Feature inference: if x exists, we can assume that y exists
if('localStorage' in window){
window.sessionStorage.setItem("this-should-exist-too", 1);
}
If you rely on the user agent, then you would have to have a map that browser X supports feature Y
Feature detection is attempting to determine if a feature exists. For example, if the user's browser supports LocalStorage or the geolocation APIs.
if (navigator.geolocation) {
// geolocation possible.. do some stuff
}
Feature inference is assuming that because you've detected one feature that you can use other features. For example if you detect the geolocation API maybe you'd assume your user is on a modern browser and so now LocalStorage is available. It's usually bad to assume so you're much better off just using feature detection for each feature you want to take advantage of, and have a fallback strategy in place in the event a feature isn't available. Even if a user has a modern browser with geolocation doesn't mean they're going to allow your app to use it so plan accordingly.
User agent string is just reading the stupid little string that each browser sends along and then you can compare that string with some known browsers you're targeting. Generally this is a super old way of doing things and is easily spoofed so you'd have to have a very specific reason to want to go that route (maybe in a load testing environment or something). See the wiki on the topic http://en.wikipedia.org/wiki/User_agent
You would access it in javascript similar to:
navigator.userAgent
© 2022 - 2024 — McMap. All rights reserved.
feature detection vs. user agent
, like Browser detection versus feature detection – Allix