baliga ([info]baliga) wrote,

Javascript Browser Detection - Best Practices

Modern browser providers are introducing their own standards and own ways to access different DOM properties. I see two options to write a cross browser javascript.

  1. Push browser specific javascript from server.
  2. Javascript based Browser testing on the client.

Some browser allow configuration of userAgent sent to the server. Web clients can lie to the server because of this. First approach is a very bad idea.

Browser testing on the client using Javascript is a good practice. There are many ways of performing this test. Each has its own pros and cons.

Many scripts does a comparision of navigator.userAgent string. This is having the same issues are first approach. userAgent string provided by the browser to Javascript is not standard or can be overridden in the browser configuration.

I personally like performing the object detection. For example, If I want to get the position style attribute of a element,

var pos = "";
if (elem.currentStyle) {

  // Currently supported by IE > 5.x
  var pos = elem.currentStyle.position;

} else if (document.defaultView) {

  // Currently supported by gecko based browsers
  pos = document.defaultView.getComputedStyle(elem, null).getProperty("position");

} else {

  // Not a supported browser

}

Is there any better approach for it? Is there any Javascript library which give a browser independent read/write access to various properties?


  • Post a new comment

    Error

  • 0 comments
Create an Account
Forgot your login or password?
Facebook Twitter More login options
English • Español • Deutsch • Русский…