Java Reference
In-Depth Information
Feature Detection
Programming in JavaScript can be something of a moving target as the APIs it uses are in a
constant state of flux. And there are new APIs being developed as part of the HTML5 spe-
cification all the time (more on these in
chapter 14
). Browser vendors are constantly adding
support for these new features, but they don't always keep up. What's more, some browsers
will support certain features and others won't. You can't always rely on users having the
most up-to-date browser, either.
One way of circumventing this problem is through
browser sniffing
. This involves using
the string returned by
window.navigator.userAgent
property that we met in the
last chapter to identify the user's browser. The relevant methods can then be used for that
browser. This approach is problematic, however, and not recommended because the user
agent string cannot be relied upon. Additionally, the pace of browser development makes it
difficult to keep up with what features are supported across browser versions.
A better way to determine browser support for a feature is to use
feature detection
. This
is done using an
if
statement to check whether an object or method exists before trying to
actually call the method. For example, say we want to use the shiny new
unicorn
API, we
would wrap any method calls inside the following
if
block:
if (window.unicorn) {
unicorn();
}
This ensures that no error occurs if the browser doesn't support the method, because ref-
erencing a nonexistent method such as
window.unicorn
(without the parentheses) will
return
undefined
. As it's a falsy value, the
if
block won't run, but calling the method
unicorn()
(with parentheses) will cause an exception to be thrown. This guarantees that
the method is only called if it actually exists and avoids any exceptions being thrown.