:web design/

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:


Site Meter
Valid XHTML 1.0!Valid CSS!Level Triple-A conformance with WAI guidelines