A Complete Guide to Web Design

(やまだぃちぅ) #1
Handling Multiple Browsers 383

JavaScript

Handling Multiple Browsers

Web Design in a Nutshell, eMatter Edition

Handling Multiple Browsers


Unlike with CGI scripts, which run on the server and don’t require any particular
intelligence on the part of the browser, JavaScript code is completely dependent
on browser support. If you put a JavaScript on your page, browsers that don’t
understand JavaScript won’t know what to do with it. These browsers will inter-
pret the code as straight text and the result will be rather unpleasant.


Not as unpleasant, however, as if your code isn’t completely understood by a Java-
Script-aware browser. Unfortunately JavaScript support is not an on-or-off option;
Netscape has released several different versions of JavaScript with varying levels of
support in each browser. To make matters worse, Microsoft’s support for Java-
Script has at times lagged behind Netscape’s, sometimes outpaced it, and
sometimes it’s just been different. Fortunately, JavaScript provides ways to hide
scripts from non-supporting browsers and to target the browsers that understand
specific JavaScript elements.


Hiding JavaScript from Old Browsers


It’s quite simple to hide JavaScript from old browsers: simply comment out the
script, as shown:


<SCRIPT LANGUAGE=JavaScript>
<!—-
JavaScript code here
// -->
</SCRIPT>

It’s important that the comment codes () be on their own lines. If
you put the comment code on the same line as some code, that line will be
commented out and the script won’t work.


Checking for Browsers


If you have a script that you know works in Netscape 4 but doesn’t work in any
other browser, you may want to check browser versions and serve your script to
Netscape 4 users and some straight HTML to other browsers. The first step is to
check the browser’s name and number and to assign that information to a
variable:


<HTML>
<HEAD>
<TITLE>A Page</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
<!--

bName = navigator.appName;
bVer = parseInt(navigator.appVersion);

if (bName == "Netscape" && bVer >= 4) br = "n4";
else if (bName == "Netscape" && bVer == 3) br = "n3";
else if (bName == "Netscape" && bVer == 2) br = "n2";
Free download pdf