Producing web pages
* HTML CSS DHTML XHTML A to Z of tags        Accessibility          Design

Adding scripts to your pages

A script is just a bit of code that runs when the browser loads an HTML page or when an event, such as the click of a button, happens. A script allows you to do to all sorts of things. For example:

  • Change the contents of the page dynamically
  • Process a form as users enter information. For example, a script may dynamically fill out parts of a form based on the values of other fields or make sure that input data conforms to predetermined ranges of values, that fields are mutually consistent, etc.
  • Carry out processing that is triggered by events that affect the document, such as loading, unloading, element focus, mouse movement, etc.
  • Link to form controls (e.g. buttons) to produce graphical user interface elements

To add scripts to pages, you use the <script> tag. You can include the full source code of a script in the page or you can point to a file that contains the script.

Here's a little script:

<script language="JavaScript">
document.write("Hello, Webmaster.")
</script>

The language attribute tells the browser that the code is in JavaScript and not another scripting language such as VBScript. The code follows this tag and the script ends with the </script> tag. You can have as many <script> tags as you need; just remember to close each tag before you go on.

Some older browsers don't recognise the <script> tag so they display the text of your script as lines of text on the screen. To get around this problem, use an HTML comment. The older browsers ignore the text inside the comments but a JavaScript browser goes ahead and runs your script. Here is how to do it:

<script language="JavaScript"> 
<!-- 
document.write("Hello, Webmaster.")
//-->
</script>

Here's an example that loads an external script:

<script type="text/JavaScript" src="expand.js">

The src attribute specifies the name of the script file (expand.js). This name can include directories for a full URL.

The browser looks the <script> tag when it loads the page and executes all the code in the order in which it appears in the page. You can put the <script> tag anywhere in the HTML page but any reference to an object, such as an ActiveX Control, must appear in the text after the script tag in which you define it.

I should put your scripts in the <head> and </head> tags of your document. Your scripts then load before the page begins to display and you won't see any JavaScript errors.

You should also use the <meta> tag to specify a default scripting language for the document. For example:

<meta http-equiv="Content-Script-Type" 
content="text/javascript">

You could also have content="text/vbscript".