Next page | Contents page |

Running JavaScript

This part of the course is about the core language, not necessarily anything to do with web pages. But the most readily available environment in which to run Javascript is a web browser, so we will first look at how to use the language in a local HTML file displayed by a browser. You will need to be able to do this for the exercises in this part of the course.

As we saw in Part 1, there are 3 ways to kick off a JavaScript program from HTML:

A browser tip (Windows)

Although F5 refreshes a page, you may need Ctrl+F5 to clear the browser's cache and ensure scripts are reloaded and run from scratch.

  1. Embedded in head or body of page:
    <script type="text/javascript">
    	... the script goes here, 
    	maybe on several lines ...
  2. Included from separate file, conventional extension .js:
    <script type="text/javascript" src="mycode.js"></script>

    NB: The </script> is essential, even though there is no content. The XHTML shorthand <script src="mycode.js" /> will not work in all browsers. This is important to remember if you generate pages by XSLT (as these course pages are).

  3. As the value of an HTML event handler attribute. Eg,
    <input type="button" onclick="draw()">

The first of these may be used repeatedly to scatter parts of a script throughout an HTML page. However that can become very hard to read and maintain, so the second and third methods are preferred.

When you examine other people's code you will often see the attribute language="javascript" in the script tag instead of type="text/javascript". That is a mistake. There is a language attribute but you would only use it if you wanted to make it clear that you are using certain features of the language which only appeared with a particular version. So as well as the type attribute you could put, say, language="javascript1.5" if you are relying on something that only appeared in version 1.5. That would tell the browser not to bother with this bit of script if it cannot do that. However, these days there is little point because you can always test whether something exists before trying to use it and do something different if it does not. We saw an example with the graphics in Part 1: whether function getContext() exists in the browser.

So the rule is: always use the type attribute and forget about the language attribute.

Scripting disabled

Users may switch off the scripting capability of their browser. Use a <noscript> element to tell them when this has happened. Eg,

<noscript>You are missing some important features of our site because either your browser does not support Javascript or you have disabled support for scripts.</noscript>

Next page | Contents page |