HTML and CSS Reference
In-Depth Information
This example suffers many of the same problems as that of our user agent sniffer.
Object detection is a very useful technique, but not to detect
browsers
.
Although unlikely, there is no guarantee that browsers other than Internet Ex-
plorer won't provide a global
ActiveXObject
property. For instance, older ver-
sions of Opera imitated several aspects of Internet Explorer, such as the propri-
etary
document.all
object, to avoid being blocked by scripts that employed bad
browser detection logic.
The basic premise of browser detection relies on upfront knowledge about the
environments that will run our scripts. Browser detection, in any form, does not
scale, is not maintainable, and is inadequate as a cross-browser scripting strategy.
10.1.3 The State of Browser Sniffing
Unfortunately, browser detection still exists in the wild. Many of the popular libraries
still to this day use browser detection, and even user agent sniffing, to solve certain
cross-browser challenges. Do a search for
userAgent
or
browser
in your favorite
JavaScript library, and more likely than not, you will find several decisions made
based on which browser the script thinks it's faced with.
Browser sniffs cause problems even when they are used only to make certain
exceptions for certain browsers, because they easily break when new browser ver-
sions are released. Additionally, even if a sniff could be shown to positively iden-
tify a certain browser, it cannot be easily shown to
not
accidentally identify other
browsers that may not exhibit the same problems the sniffs were designed to smooth
over.
Because browser detection frequently requires updating when new browsers
are released, libraries that depend on browser sniffs put a maintenance burden on
you, the application developer. To make the situation even worse, these updates are
not necessarily backwards compatible, and may require you to rewrite code as well.
Using JavaScript libraries can help smooth over many difficult problems, but often
come at a cost that should be carefully considered.
Object detection, although no good when used to detect browsers, is an excellent
technique for detecting
objects
. Rather than branching on browser, a much sounder
approach is branching on individual features. Before using a given feature, the script
can determine whether it is available, and in cases in which the feature is known to
have buggy implementations, the script can test the feature in a controlled setting
to determine if it can be relied upon. This is the essence of feature detection.