Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

12. Browser Detection > Feature Detection

Feature Detection

Looking to use a more sane approach to browser-based conditionals, developers turned to a technique called feature detection. Feature detection works by testing for a specific browser feature and using it only if present. So instead of doing something like this:

// Bad
if (navigator.userAgent.indexOf("MSIE 7") > -1) {
    // do something
}

you should do something like this:

// Good
if (document.getElementById) {
    // do something
}

There is a distinction between these two approaches. The first is testing for a specific browser by name and version; the second is testing for a specific feature, namely document.getElementById. So user-agent sniffing results in knowing the exact browser and version being used (or at least the one being reported by the browser) and feature detection determines whether a given object or method is available. Note that these are two completely different results.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial