advertisement -- please support sponsors

programming:
importing scripts from other files

How can I use JavaScript functions defined in an external file?

When JavaScript and the <script> tag were first introduced, users were promised that they would eventually be able to use external JavaScript source files in their web documents. Netscape Communications has made good on their promise by implementing this feature in Netscape Navigator 3.

Now, instead of placing JavaScript code between the <script> and </script> tags, you can save it in a separate file and add a src property to the <script> tag that tells the browser where to find it, as demonstrated below:

<script src="mycode.js"></script>
This makes it possible for multiple HTML files to share the same JavaScript code. In order for this feature to work, however, there are several requirements which must be met:

  1. The external source file name must end with the extension .js.
  2. The .js file must contain only JavaScript code and no HTML.
  3. The client's browser must be Netscape Navigator 3.
  4. If the .js file is downloaded from a server, the server must map it to the application/x-javascript MIME type.

Requirements (1) and (2) are easy to achieve, since you have complete control over the files.

Requirement (3) is difficult to enforce, since it means you have to alienate all non-Netscape 3 users -- or at the very least generate a separate set of web pages for them. How many times have you downloaded a web page and seen a message warning you that "this document looks best on" some other browser besides yours? If your web page uses functions defined in external JavaScript files, your document should probably include the message, "This document works only on Netscape 3." Of course, even if you don't warn the other browser users, JavaScript error windows popping up all over the place will probably clue them in.

Requirement (4) might be a little tricky, but not impossible. It means that you may have to contact your web server's administrator and ask him or her to configure the MIME type for you. If your pages use external JavaScript files and they work on your local file system (i.e., your hard disk) but not on your server, chances are that the web server is not serving .js files correctly.

One last note about using the <script> tag's src property: If you use it, you still need the closing </script> tag. Browsers that support external JavaScript files ignore everything between the enclosing script tags when external files are specified. This makes it possible to warn other JavaScript-capable browser users that their browser is about to freak out:

<script src=mycode.js>
// Netscape 3 will execute
//
statements from mycode.js,
//
but not the statements below.

alert ("This page won't work on your browser.");
alert ("Get Netscape 3!");
history . back ();
</script>

Charlton Rose
12/13/96