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 interpret 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 JavaScript-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 JavaScript 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 (<!- - and //- ->) 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 ...

Get Web Design in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.