jQuery in Action

156
CHAPTER 6
jQuery utility functions
Browser detection can be the following:
Imprecise--Accidentally blocking browsers that our code would work within
Unscalable--Leading to enormous nested if and if-else statements to sort
things out
Inaccurate--Due to users spoofing false user agent information
Obviously, we'd like to avoid using it whenever possible.
But what can we do instead?
What's the alternative?
If we think about it, we're not really interested in which browser anyone is using,
are we? The only reason we're thinking about browser detection is so that we can
know which browser capabilities we can use. It's the capabilities of a browser that
we're after; using browser detection is just a ham-handed way of trying to deter-
mine those capabilities.
Why don't we figure out what those capabilities are rather than trying to infer
them from the browser identification? The technique known broadly as object
detection
allows code to branch based on whether certain objects, properties, or
even methods exist.
Let's think back to our chapter on event handling as an example. We remem-
ber that there are two advanced event-handling models: the
W3C
standard
DOM
Level 2 Event Model and the proprietary Internet Explorer Model. Both models
define methods on the
DOM
elements that allow listeners to be established, but
each uses different method names. The standard model defines the method
addEventListener()
, whereas the
IE
model defines
attachEvent()
.
Using browser detection, assuming that we've gone through the pain and
aggravation of (maybe even correctly) determining what browser is being used,
we could write
...
complex code to set flags: isIE, isFirefox and isSafari
...
if (isIE) {
element.attachEvent('onclick',someHandler);
}
else if (isFirefox || isSafari) {
element.addEventListener('click',someHandler);
}
else {
throw new Error('event handling not supported');
}


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.