Next page | Contents page |

Where to start a program

Attributes

The starting tag of an HTML element can often have extra bits written inside it, called attributes. Each consists of a space character followed by the name of the attribute, then an equals sign, then a value enclosed in double quotes. So our first examples occur in the <script> elements here. These are attributes:

type="text/javascript"

src="myprogram.js"

Strictly speaking the quotes are unnecessary but always using them is a good habit to get into.

There is an HTML element called <script>. It can be used in either of the following ways.

  1. Embedding program code into the body wherever it is needed:
    
    <html>
      <head>
        <title>My page</title>
      </head>
      <body>
        <script type="text/javascript">
    Some JavaScript statements - 
    maybe over many lines
        </script>
        <p>A paragraph of text.</p>
        <script type="text/javascript">
    Some more JavaScript statements
        </script>
        <p>Another paragraph of text.</p>
      </body>
    </html>
    
  2. Putting the program code in separate files, to be included by the head section of the HTML:
    
    <html>
      <head>
        <title>My page</title>
        <script type="text/javascript" src="myprogram.js"></script>
      </head>
      <body>
        <p>A paragraph of text.</p>
        <p>Another paragraph of text.</p>
      </body>
    </html>
    

Mixing JavaScript and HTML can easily become very hard to read and maintain. Future maintenance and enhancement are important considerations in programming: lay your programs out as clearly as possible.

For that reason the second method should be used whenever possible. In the second example above the program is loaded from a file called myprogram.js which is in the same directory as index.html. So it will be done like that in the next exercise.

HTML element structure with one attribute

<elementName attributeName="attributeValue">content</elementName>

By the way

For those who know some HTML:

  1. Do not be tempted to use the shorthand closure for the script tag. It totally confuses some browsers.
  2. It used to be necessary to use comment markers to ensure that the script was not read as HTML. Browsers have been clever enough to avoid that for many years now, so that will not be done here.
Next page | Contents page |