The worst abomination onto JS is probably browser sniffing: It’s a pretty simple technique that’s easy to understand which is probably why beginners tend to use it, however it’s also a technique that a) requires a lot of testing, b) requires a lot of updates and c) goes completely bonkers when new browsers are released.
What browser sniffing (a.k.a. useragant sniffing) does is “ask” the browser about itself and then taking appropriate measures. Seems simple, right?
Well if it is so simple, then what would happen if you ask a browser if it is a “Mozilla”… Surprise! Pretty much all major browsers (including Internet Explorer) claim to be Mozilla. So let’s ask about MSIE to make sure which Mozillas are actually Internet Explorer. Oops, Opera and a few others report that too. OK, then how about finding out which ones are really Mozilla by looking for “Gecko”. Oh, Safari says it’s “like Gecko”. If you want an almost complete list, have a a look here.
You see: it doesn’t work and it’s really a shame that people still use this first-grader technique if there’s a much easier alternative: Method sniffing.
For example, lets say we want to use the addEventListener method and as a fallback the attachEvent method, then we simply create a wrapper function:
else if(obj.attachEvent!=undefined) obj.attachEvent(“on”+type,callback);
else alert(“Sorry, your browser is not supported”);
And that’s it. And it works for pretty much everything, except for some strange HTML behaviours. Now my minions: Spread the word.
The next time I’ll be looking at the scope of Variables in JS… a topic that isn’t understood by more than a handfull of people, eventhough it’s not that difficult. See you next time.