Implementing feature detection
Feature detection involves working out whether a browser supports a certain block of
code, and running different code depending on whether it does (or doesn't), so that the
browser can always provide a working experience rather than crashing/erroring in some
browsers. This article details how to write your own simple feature detection, how to use a
library to speed up implementation, and native features for feature detection such as
@supports .
Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages; an idea of the
high-level principles of cross-browser testing.
Objective: To understand what the concept of feature detection is, and be able to implement
suitable solutions in CSS and JavaScript.
The concept of feature detection
The idea behind feature detection is that you can run a test to determine whether a
feature is supported in the current browser, and then conditionally run code to provide an
acceptable experience both in browsers that do support the feature, and browsers that
don't. If you don't do this, browsers that don't support the features you are using in your
code may not display your sites properly or might fail altogether, creating a bad user
experience.
Let's recap and look at the example we touched on in our Handling common JavaScript
problems — the Geolocation API (which exposes available location data for the device the
web browser is running on) has the main entry point for its use, a geolocation property
available on the global Navigator object. Therefore, you can detect whether the browser
supports geolocation or not by using something like the following:
JS
if ("geolocation" in navigator) {
[Link](function (position) {
// show the location on a map, such as the Google Maps API
});