HTML and CSS Reference
In-Depth Information
Listing 12.7 Checking for support upfront
(function () {
var xhr;
var ajax = tddjs.namespace("ajax");
var options = [/* ... */]; // Same as before
for (var i = 0, l = options.length; i < l; i++) {
try {
xhr = options[i]();
ajax.create = options[i];
break;
} catch (e) {}
}
}());
With this implementation in place, the try/catch will only run at load time. If
successfully created, ajax.create will call the correct function directly. The test
still runs green, so we can focus on the next requirement.
12.3.4 Stronger Feature Detection
The test we just wrote is bound to work as long as it is run with the basic JsTestDriver
setup (seeing as JsTestDriver requires the XMLHttpRequest object or equivalent).
However, the checks we did in Listing 12.3 are really feature tests that verify the capa-
bilities of the returned object. Because we have a mechanism for verifying the object
only once, it would be nice to make the verification as strong as possible. For this
reason, Listing 12.8 performs the same tests in the initial execution, making us more
confident that a usable object is returned. It requires the tddjs.isHostMethod
method from Chapter 10, Feature Detection, in lib/tdd.js .
Listing 12.8 Adding stronger feature detection
/* ... */
try {
xhr = options[i]();
if (typeof xhr.readyState == "number" &&
tddjs.isHostMethod(xhr, "open") &&
tddjs.isHostMethod(xhr, "send") &&
tddjs.isHostMethod(xhr, "setRequestHeader")) {
ajax.create = options[i];
break;
}
} catch (e) {}
 
Search WWH ::




Custom Search