HTML and CSS Reference
In-Depth Information
isn't your main priority. Rather, feature detection allows our scripts to know if they
will succeed or not. This knowledge can be used to avoid script errors and broken
web pages.
Keep in mind that not only will the feature test avoid trouble in ancient browsers,
it is also a safeguard for new browsers with similar problems. This is especially
interesting in light of the growing number of mobile devices with JavaScript support
surfing the web. On a small device with limited resources, skipping features in either
the ECMAScript, DOM, or other specifications is not unthinkable. Now I don't
think String.prototype.replace will regress anytime soon, but the sample
use technique is an interesting one.
In Chapter 7, Objects and Prototypal Inheritance, we already saw another ex-
ample of feature testing when we defined the Object.create method, which is
already supported by a few browsers and will appear in more browsers as support
for ECMAScript 5 becomes more widespread.
10.2.5 When to Test
In the preceding sections we have seen different kinds of tests. The addEvent-
Handler method applied feature tests at runtime, whereas the safeguard for
Date.prototype.strftime was employed at loadtime. The runtime tests
performed by addEventHandler generally provide the most reliable results be-
cause they test the actual objects they operate on. However, the tests may come
with a performance penalty and, more importantly, at this point it may already be
too late.
The overall goal of feature detection is to avoid having scripts break a web-
site beyond repair. When building on the principles of unobtrusive JavaScript, the
underlying HTML and CSS should already provide a usable experience. Applying
feature tests up front can provide enough information to abort early if the envi-
ronment is deemed unfit to run a given enhancement. However, in some cases,
not all features can be reliably detected up front. If we have already partially ap-
plied an enhancement only to discover that the environment will not be successful
in completing the enhancement, we should take steps to roll back the changes
we made. This process may complicate things, and if possible should be avoided.
The roll-back situation can sometimes be avoided by deferring actions that would
be destructive if applied alone. For example, in the case of the tabbed panel in
Chapter 9, Unobtrusive JavaScript, we could hold off adding the class name to the
panel that triggers a design that relies on the panel being fully loaded until we know
that it can do so successfully.
Search WWH ::

Custom Search