|MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA|
Recipe 5.7: Detecting Object Property and Method Support
NN 2, IE 3
You want scripts to run on all browsers that support the object properties and/or methods that your scripts address, and to degrade gracefully in other browsers.
Surround the script statements that reference
potentially incompatible object properties or methods with
It is not advisable, however, to use the simple existence test for an
object's property in an
References to object methods take the same form as references to functions: the name of the method without the parentheses. If the method exists, the reference evaluates to a valid object type and the conditional test succeeds:
For example, to protect scripts written with W3C DOM element-referencing from
tripping up older browsers, you can wrap function execution inside conditions
that test for the existence of the
To save some bytes on the page and extraneous expression evaluation, you can also set a Boolean global variable as the page loads to use in later condition statements:
Be careful about the assumptions you make when you qualify a browser for an
object and one of its properties or methods. For instance, it would be a mistake
to assume that because the browser indicates support for the
Don't be afraid to nest multiple levels of object and property/method detection in a function. You can see examples of this when processing events for the incompatible IE and W3C event models (for more, see Recipe 9.1). But always make sure that your functions are structured in such a way that any one condition failure is handled gracefully so that no script errors accrue in the absence of support for your desired object, property, or method.
The W3C DOM specification includes facilities
to help scripts know what level of support is offered by the browser. Every
element object has an
But this test is not rigorous enough for most scripters. The standards contain numerous optional features, whose omission still allows a browser maker to claim full conformance with the standard. The only way to assure complete support for modern scriptable features is via the more explicit object, property, and method condition testing.
Recipe 5.6 for detecting object support; Recipe 4.6 for special condition
expressions that evaluate to
Return to the Web Development DevCenter.