External script files
If you have looked at the article on Cascading Style Sheets, you will have seen that the best way to use CSS, especially in a large site, is by linking many pages to one external style sheet. That way, global styles can be changed easily by adjusting one style sheet rather than having to fix every single document.
It might have occurred to you that it would be useful if the same thing could be done with JavaScript; many sites use JavaScript, often similar functions on many pages — just as with style sheets, it could save a lot of work if the functions could be held in an external text file.
Well, they can, but it is done slightly differently. While links to an external CSS file are made using the <link> element, the <script> element itself is used to link to an external JavaScript library file. When scripts are included within a document, this is done like so:
<script type="text/JavaScript"> //the JavaScript function goes here </script>
If you have not looked at any JavaScript before, // is the JavaScript comment identifier. The JavaScript function can be placed in the document head or in the body — usually the head, but sometimes the body is appropriate. A link to an external library file should be placed in the head of the document.
To link to an external file, the first thing to do is create the JavaScript library file. This should be a plain text file, called something like script.js, perhaps. Once that has been done, insert a <script> element in the document head like so:
<script type="text/JavaScript" src="script.js"></script>
The <script> element is almost identical in this use as in the previous case. Apart from the lack of content, the difference is that the element now uses a src attribute to specify the source file. This attribute is exactly the same as the src attribute which should be very familiar from the <img> tag. As with images, the sensible approach is to create a directory which will store all the scripts for the site.
Important points to remember in linking to a script library file:
- Any calls to functions held in the library file must follow the link to the file since otherwise the function doesn’t exist as far as the document is concerned!
- You need to take more care in getting the name of functions right, since you cannot simply glance at the top of the document to check it. Depending on how you name JavaScript functions, this might be an area which trips you up!
- You may hit problems with older browsers that can’t handle this technique — Netscape 2 & 3 spring to mind. If you have never seen the older versions of Netscape hit a JavaScript error, it is scary: windows opening all over the place, completely stopping the user from doing anything. There is some consolation in the fact that these browsers account for less than 1% of users — but you may be designing a page for a group with a higher proportion of such users, so bear this in mind.
© DC 2000. All rights reserved.


