Sunday, July 13, 2008

How to become browser independent?

How to become browser independent?

(This blog entry intended for the young web developers)
If you are a web developer and often write JavaScript code then you must be aware of the fact that JavaScript behaves differently on different browsers.
Actually each of the browsers has their own set of JavaScript implementation. That’s makes the JavaScript programmer’s life damn difficult while writing the JavaScript code.

The most common way a JavaScript developers fight against the browser dependency is by doing a Null check on each variable before executing on it.
For example
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i< XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}


Here you can see, author is brute forcing to get a simple XMLHttpRequest instance. Because in different browsers XMLHttpRequest object can be retrieved in different ways.

I found a much simpler way to become browser independence in terms of JavaScript as well as in terms of CSS.
Write your JavaScript on top of the any existing JavaScript framework which is coded for browser independence. A question is which JavaScript library is coded for browser independence? Answer is YUI.
Yes, YUI (Yahoo User Interface library) is freely available library, coded and maintained by Yahoo.
This library is a result of yahoo’s 20 years (more than that I guess) of experience with web technologies. One of the best part of this library is it is hosted on yahoo website. Additionally you can download and can serve from your website too.