Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between feature detection, feature inference, and using the UA string [closed]

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?

like image 544
professormeowingtons Avatar asked Nov 20 '13 19:11

professormeowingtons


2 Answers

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
}
like image 89
R. Oosterholt Avatar answered Oct 30 '22 21:10

R. Oosterholt


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

like image 6
Rob M. Avatar answered Oct 30 '22 20:10

Rob M.