Browser detection is when you attempt to detect a browser. This is unreliable and has many problems. What if a new browser comes along? Can you really expect to detect every single browser on the planet? I have even seen scripts that try to detect browser versions. Imagine their annoyance and distress when IE7 came out ("It works fine in IE6, but won't work in IE7"). So what's the solution?
Easy, use object detection instead. In object detection, we check for the existence of an object. If it exists, we code with it. If not, we can try something else or maybe check for the existence of another object. This way we can support as many browsers as possible without having to worry about what a particular browser may support. For example, in AJAX, we can check for the existence of the XMLHttpRequest object:
Expand|Select|Wrap|Line Numbers
- if (window.XMLHttpRequest) { ...
Expand|Select|Wrap|Line Numbers
- else if (window.ActiveXObject) {
Use the standards
Standards are there for a reason. Use them. This will make your code work in most browsers. If, for some reason, you're coding the standard way and your code isn't working, chances are that the browser will be Internet Explorer.
However, since it is the most popular browser, you have no choice but to support it. The good news is that being popular means that the bug/quirk will most probably be documented (not in the official documentation, but somewhere on the Web).
Check for the existence of the object, method, etc. and code accordingly. If it's simply a bug, then use try..catch statements to catch the error in the buggy browser and use the fix/solution. If there's a solution which doesn't affect any other browser, you could use that instead.
As an example, take the case of appending an option at the end of a select object. The standard method uses two arguments - the second one being null, but that won't work in IE, so you can use the following code:
Expand|Select|Wrap|Line Numbers
- try {
- selObj.add(optObj, null);
- } catch(e) { // for IE
- selObj.add(optObj);
- }
If you find these difficult to decipher, the W3Schools HTML DOM reference points out if something is part of the W3C standard. The Mozilla Core Javascript 1.5 Reference is also useful for the core language.
There are more than two browsers
"Really?!", you may ask sarcastically. However, judging by questions commonly asked in the forums, many seem to only worry about Internet Explorer and Mozilla Firefox. Some, it's sad to say, still think it's enough to support Internet Explorer only.
Have a look at a list of browsers to see that there are a lot more than just two.
A web application or a website of any sort should attempt to support as many web browsers as possible. Again, as mentioned earlier, if you follow the standards, this task will be made a lot easier. All you may need to do is to adjust slightly to allow for a few bugs or quirks.