Monday, December 18, 2006

Browser sniffing is [or should be] dead

"Sniff the right way

One solid alternative [to browser sniffing] is feature sniffing. This is the other solution mentioned by the “Gecko is Gecko” folks, and it’s vastly superior; instead of looking at the user-agent string and redirecting if it’s not in your “approved” list, you instead use JavaScript to test for the features you want (and, these days, browser sniffing is much more about JavaScript — particularly AJAX capabilities — than anything else). This is a concept that’s been kicking around for years, and which has had one or two high-profile articles written about it (including one by JavaScript guru Stuart Langridge, helpfully linked by the “Gecko is Gecko” site).

The nice thing about feature sniffing is that it’s almost completely foolproof: a browser will lie out of both sides of its mouth about whether or not it’s IE, but its JavaScript engine won’t lie about whether it supports getElementById. There are a couple of wrinkles in this rosy picture (notably Safari which, last I checked, exposes a method called preventDefault on DOM events, even though it doesn’t actually do what preventDefault is supposed to do), but I’d be willing to bet it’s as least as effective, percentage-wise, as sniffing for the “big four” (IE, Firefox, Safari and Opera) and it has the advantage of being future-proof: when the browser market changes, you have to adjust your sniffing scripts. But so long as you’re testing for actual features, you never have to update; getElementById isn’t going to get renamed any time soon.

And to really hammer it home, keep in mind that this is by far the most effective way to implement AJAX effects. Versions of IE prior to 7 expose XMLHttpRequest in a slightly different fashion from other browsers, so the browser-sniffing method relies on being able to absolutely differentiate IE so you can use the correct invocation. Of course, lots of other browsers like to masquerade as IE in their user-agent strings, so that’s out the window — trying to use IE-style invocation in non-IE browsers will just throw JavaScript errors at your users, and then they’ll complain (if you’re lucky) or take their money and their ad-viewing eyeballs somewhere else (if you’re not). Meanwhile, a few short lines of JavaScript which determine where the XMLHttpRequest object lives are all that’s needed to effectively work out how to do AJAX. "

The B-List: Sniffle:

No comments: