JavaScript Object Detection (2/3) | WebReference

JavaScript Object Detection (2/3)

To page 1current pageTo page 3
[previous] [next]

Object Detection in the New Browser Age

Get the picture? Object detection is not as clear cut as we would like it to be. In an ideal world, we would not need to separate browsers from each other. Browsers would simply render the page exactly the same no matter what markup was used. Despite browser manufacturers making considerable progress in supporting Web standards, the practical application of our endeavors typically means some form of browser separation. It's frustrating, I know! Unfortunately, until we completely enter the new age where all browsers adequately support Web standards, we as developers and designers have to spend energy, time and ultimately money (if you're looking for a hack, you typically don't get paid for it by the client) to find ways to make our pages similar to each other, in as many browsers and platforms as we can.

Consequently, the task in front of us is to find better ways to separate out browsers from each other. The good news is that with a little thought we can quite easily create object detection routines that will do the job for us. Let us investigate further by first looking at a commonly used object detection routine and then proceeding to further separate out browsers.

A generic method of separating between standards based browsers, Internet Explorer browsers and a Netscape 4 browser is to use something like this:

if (document.getElementById) { 
// do something here
}
else if (document.all) { 
// do something here
}
else if (document.layers) {
// do something here
}

The first condition allows browsers that support the document.getElementById() method. Included in this condition would be Internet Explorer 5+ on both Windows and Mac platforms, Netscape 6 and Opera 6+.

The second condition allows the developer to code for Internet Explorer 4. Since Internet Explorer 5 and above supports the document.getElementById() method, these browsers will be captured by the first condition, so we can safely assume that these browsers will ignore the second condition.

The third conditional statement captures Netscape 4 based browsers. Since Netscape 6 is captured by the first condition and does not support the document.layers condition, the code below this conditional statement will be specific to Netscape 4.

If we are developing a page that does not require complex scripting routines or advanced layout techniques, the above typically suffices. But as we have already seen there are scenarios where further browser separation is required.


To page 1current pageTo page 3
[previous] [next]

Created: February 3, 2003
Revised: February 3, 2003

URL: https://webreference.com/programming/javascript/detection/2.html