A few words about Javascript

I’m a bit of a Javascript fan and since I don’t have anything better to do right now I though I could tell you about a few typical errors that even the guys over at Google, along with 99% of all pages I know, make.

The problem is that people learn Javascript as well, a Script language, not a proper programming language… which is a shame because Javascript itself is probably one of the most comfortable languages I know. And because they don’t see it as a proper programming language they just hack their code until it works… for now.

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.

In Javascript, every function or method that does not exist has the value “undefined”. So if you want to use something that you are afraid isn’t available everywhere, you just ask if the browser supports it directly, instead of asking for the browser and then assuming that a certain browser supports this or that.

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:

function wrapperAddEventListener(obj,type,callback){
if(obj.addEventListener!=undefined) obj.addEventListener(type,callback,false);
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.

One thought on “A few words about Javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.