Browser Compatibility: Object Detection - Doc JavaScript
Object Detection
Browser detection is not recommended because it checks what browser the user is running, not what features are supported. So if your script depends on browser detection to decide whether or not to execute a specific function or script segment, it might not work with future browers. The number of browsers and browser versions is constantly growing, and so is the number of inconsistent features. Furthermore, you must be a JavaScript hacker to know exactly what features are supported by each browser. Is window.onerror
supported by Netscape Navigator 2.0? How about Microsoft Internet Explorer 3.0? With object detection you don't need to know!
As you already know, if you refer to an object (or a property, method, function, etc.) that is not supported, the browser cannot execute the script, and it displays a very annoying error message. Object detection simply checks if an object exists before you use it in the script. We used object detection in our column "Universal JavaScript Rollovers" to find out if the browser supports the document.images
object before using it to swap the desired image:
if (document.images) {
// rollover script here
}
The general syntax for object detection is:
if (the name of the required object) {
// statements that use that object
}
A few restrictions apply to the object in the conditional statement:
- It cannot be specified as a top-level object. For example, you must use
window.onerror
instead ofonerror
, even though they have the same meaning. - Its parent object must be specified, and must exist. For example, you should not use
document.images.length
, because the browser might not support the parent object,document.images
. If you need to detect a nested object, you can take advantage of JavaScript's short-circuit evaluation, as in:
When you combine more than one conditional expression with a Boolean "and" operator (if (document.images && document.images.length) { // additional statements here }
&&
), the JavaScript interpreter stops evaluating the entire condition when one of the sub-expressions evaluates tofalse
. In this case, ifdocument.images
evaluates tofalse
(meaning that it does not exist), the interpreter does not continue, sodocument.images.length
is not evaluated (thus, no error is generated if the browser does not support the parent object,document.images
).
We all know that an if
statement requires a Boolean value. So why does it work with objects? The answer is very simple. An object that does not exist has a null
value, which is a special one, because it converts to false
when used in a statement that requires a Boolean expression.
Created: November 4, 1997
Revised: December 4, 1997
URL: https://www.webreference.com/js/column6/object.html