Ultimately, your best approach is to determine what
feature you need for any given bit of JavaScript code, and then make sure
that the browser has that feature.
For example, we know that some browsers can do image swaps and others can't. Good thing this ability is easy to detect: just make sure that the browser has the document.images object:
if (document.images)
{
do lots of image swap stuff
}
This makes sure that your image-swap code will be
run only by browsers that support image swaps. If the document.images
object doesn't exist, the if test fails and the code doesn't run.
This sort of trick works for methods and functions, too. Not all browsers have every method. For example, in Netscape 4 you can actually move windows around the screen using the window.moveTo() method. If you want
to check to see if that method exists before you invoke it, do
this:
if (window.moveTo)
{
make that window fly
}
By making sure the browser supports the feature you want to use before you invoke it, you ensure that your script will work without
any obnoxious script errors. By employing a feature-checking strategy, rather than a browser-checking one, you don't have to keep track of the capabilities of every browser in every version on every platform.
OK, that's all about browser detection. But while we're on the topic
of browsers, let's take a look at another browser-centered object:
the History object.
next page»