Using Feauter Detection
Back in the dark days before the W3C DOM evolved to its current state, JavaScript developers were forced into horrible code contortions to try to cope with browsers’ different DOM implementations. It was not uncommon for scripts to be written almost as two or more separate programs, the version to be executed only being decided after an attempt to detect the browser in use.
As you saw in your work with the navigator object in this section “DOM Objects and Built-in Objects,” browser detection is a tricky business. The navigator object contains information that can be misleading at best (and sometimes downright incorrect). Also, when a new browser or version is introduced with new capabilities and features, your browser-detecting code is usually broken once again.
Thankfully a much better way to write cross-browser code has emerged, based on objects. Instead of attempting browser detection, it’s a much better idea to have
JavaScript examine whether the particular feature you need is supported. You can do this by testing for the availability of a specific object, method, or property. In many cases it’s sufficient to try to use the object, method, or property in question, and detect the value JavaScript returns.
Here’s an example of testing for browser support of the document.getElementById() method, which you’ve already met. While getElementById() has been supported by all new browsers for some time now, very early browsers do not support this method. You can test for the availability of the getElementById() method (or any similar method or property) by using if():
if(document.getElementById) { myElement = document.getElementById(id); } else { // do something else }
If document.getElementById is not available, the if() conditional statement will switch code operation to avoid using that method.
Another, related method uses the typeof operator to check whether a JavaScript function exists before calling it:
if(typeof document.getElementById == 'function') { // you can use getElementById() } else { // do something else }
A number of possible values can be returned by typeof
You can use this technique to check for the existence not only of DOM and built-in objects, methods, and properties, but also those created within your scripts.
Note that at no point in this exercise have you tried to determine what browser your user has—you simply want to know whether it supports the objects, properties, or methods you are about to try to use. Not only is such feature detection much more accurate and elegant than so-called browser sniffing (trying to infer the browser in use by interpreting properties of the navigator object), but it’s also much more future proof —the introduction of new browsers or browser versions won’t break anything in your code’s operation.