Scripts 

Contents

  1. Designing documents for user agents that support scripting
    1. The SCRIPT element
    2. Specifying the scripting language
    3. Syntax of script content
    4. Intrinsic events
    5. Dynamic modification of documents
  2. Designing documents for user agents that don't support scripting
    1. The NOSCRIPT element
    2. Commenting out scripts
A client-side script is a program that may accompany an HTML document or be embedded directly in it. The program executes on the client's machine when the document loads, or at some other time such as when a link is activated. HTML's support for scripts is independent of the scripting language.

Scripts offer authors a means to extend HTML document in highly active and interactive ways. For example:

There are two types of scripts authors may attach to an HTML document:

Note: This specification includes more detailed information about scripting in sections on script macros.

Designing documents for user agents that support scripting 

The following sections discuss issues that concern user agents that support scripting.

The SCRIPT element 

    
<!ELEMENT SCRIPT - - CDATA      -- script statements -->
<!ATTLIST SCRIPT
  type        CDATA      #IMPLIED  -- Internet content type for
                                      script language --
  language    CDATA      #IMPLIED  -- predefined script language name --
  src         %URL       #IMPLIED  -- URL for an external script --
  >

Start tag: required, End tag: required

Attribute definitions

type = cdata
This attribute specifies the scripting language of the contents of this element. The value must be an Internet Media Type. There is no default value for this attribute.
language = cdata
Deprecated.This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
src = url
This attribute specifies the location of an external script.

The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URL value, user agents must ignore the element's contents and retrieve the script via the URL.

Scripts are evaluated by script engines that must be known to a user agent.

Specifying the scripting language 

As HTML does not rely on a specific scripting language, document authors must explicitly tell user agents the language of each script. This may be done either through a default declaration or a local declaration.

Documents that contain neither a default scripting language declaration nor a local one for a SCRIPT element are incorrect. User agents may still try to interpret the script but are not required to.

The default scripting language 

To specify the default scripting language for all scripts in a document include the following META declaration in the HEAD of a document:

<META http-equiv="Content-Script-Type" content="type">

where "type" is an Internet Media Type (see [MIMETYPES]) naming the scripting language. Examples of values include "text/tcl", "text/javascript", "text/vbscript". See [MIMETYPES] for a complete list of valid scripting language types.

In the absence of a META declaration, the default can be set by a "Content-Script-Type" HTTP header.

    Content-Script-Type: type

where "type" is again an Internet Media Type naming the scripting language.

When several HTTP headers and META elements occur, the last one defines the default scripting language. For our purposes, HTTP headers are considered to occur earlier than the document HEAD.

Local declaration of a scripting language 

It is also possible to specify the scripting language in each SCRIPT element via the type attribute. In the absence of a default scripting language specification, this attribute must be set on each SCRIPT element. When a default scripting language has been specified, the type attribute overrides it.

In this example, we declare the default scripting language to be "text/tcl". We include one SCRIPT in the header, whose script is located in an external file and is in the scripting language "text/vbscript". We also include one SCRIPT in the body, which contains its own script written in "text/javascript".

<HTML>
<HEAD>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>

References to HTML elements from a script 

Each scripting language has its own conventions for referring to HTML objects from within a script. This specification does not define a standard mechanism for referring to HTML objects.

However, scripts should refer to an element according to its assigned name. Scripting engines should observe the following precedence rules when identifying an element: a name attribute takes precedence over a id if both are set. Otherwise, one or the other may be used.

Syntax of script content 

The content of the SCRIPT element is a script, and as such, must not be evaluated by the user agent as HTML markup. The user agent must pass it on as data to a script engine.

HTML parsers must be able to recognize script data as beginning immediately after the start tag and ending as soon as the ETAGO ("</") delimiters are followed by a name character ([a-zA-Z]). The script data does not necessarily end with the </SCRIPT> end tag, but is terminated by any "</" followed by a name character.

Consequently, any HTML markup that is meant to be sent to a script engine (which may do whatever it wants with the markup) must be "escaped" so as not to confuse the HTML parser. Designers of each scripting language should recommend language-specific support for resolving this issue.

ILLEGAL EXAMPLE:
The following code is invalid due the to presence of the "</EM>" characters found inside of the SCRIPT element:

    <SCRIPT type="text/javascript">
      document.write ("<EM>This won't work</EM>")
    </SCRIPT>

A conforming parser must treat the "</EM>" data as the end of script data, which is clearly not what the author intended.

In JavaScript, this code can be expressed legally by ensuring that the apparent ETAGO delimiter does not appear immediately before an SGML name start character:

    <SCRIPT type="text/javascript">
      document.write ("<EM>This will work<\/EM>")
    </SCRIPT>

In Tcl, one may accomplish this as follows:

    <SCRIPT type="text/tcl">
      document write "<EM>This will work<\/EM>"
    </SCRIPT>

In VBScript, the problem may be avoided with the Chr() function:

    
    "<EM>This will work<\" & Chr(47) + "EM>"

Intrinsic events 

Attribute definitions

onload = script
The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.
onunload = script
The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with BODY and FRAMESET elements.
onclick = script
The onclick event occurs when the pointing device button is clicked over an element. This attribute may be used with most elements.
ondblclick = script
The ondblclick event occurs when the pointing device button is double clicked over an element. This attribute may be used with most elements.
onmousedown = script
The onmousedown event occurs when the pointing device button is pressed over an element. This attribute may be used with most elements.
onmouseup = script
The onmouseup event occurs when the pointing device button is released over an element. This attribute may be used with most elements.
onmouseover = script
The onmouseover event occurs when the pointing device is moved over an element. This attribute may be used with most elements.
onmousemove = script
The onmousemove event occurs when the pointing device is moved over an element. This attribute may be used with most elements.
onmouseout = script
The onmouseout event occurs when the pointing device is moved away from an element. This attribute may be used with most elements.
onfocus = script
The onfocus event occurs when an element receives focus either by the pointing device or by tabbing navigation. This attribute may be used with the following elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.
onblur = script
The onblur event occurs when an element loses focus either by the pointing device or by tabbing navigation. It may be used with the same elements as onfocus.
onkeypress = script
The onkeypress event occurs when a key is pressed and released over an element. This attribute may be used with most elements.
onkeydown = script
The onkeydown event occurs when a key is pressed down over an element. This attribute may be used with most elements.
onkeyup = script
The onkeyup event occurs when a key is released over an element. This attribute may be used with most elements.
onsubmit = script
The onsubmit event occurs when a form is submitted. It only applies to the FORM element.
onreset = script
The onreset event occurs when a form is reset. It only applies to the FORM element.
onselect = script
The onselect event occurs when a user selects some text in a text field. This attribute may be used with the INPUT and TEXTAREA elements.
onchange = script
The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus. This attribute applies to the following elements: INPUT, SELECT, and TEXTAREA.

It is possible to associate an action with a certain number of events that occur when a user interacts with a user agent. Each of the "intrinsic events" listed above takes a value that is a script. The script is executed whenever the event occurs for that element.

Control elements such as INPUT, SELECT, BUTTON, TEXTAREA, and LABEL all respond to certain intrinsic events. When these elements do not appear within a form, they may be used to augment the graphical user interface of the document.

For instance, designers may want to include press buttons in their documents that do not submit a form but still communicate with a server when they are activated.

The following examples show some possible control and user interface behavior based on intrinsic events.

In the following example, userName is a required text field. When a user attempts to leave the field, the OnBlur event calls a JavaScript function to confirm that userName has an acceptable value.

<INPUT NAME="userName" onBlur="validUserName(this.value)">

Here is another JavaScript example:

<INPUT NAME="num"
    onChange="if (!checkNum(this.value, 1, 10)) 
        {this.focus();this.select();} else {thanks()}"
    VALUE="0">

Here is a VBScript example of an event handler for a text field:

    <INPUT name="edit1" size="50">    
    <SCRIPT type="text/vbscript">
      Sub edit1_changed()
        If edit1.value = "abc" Then
          button1.enabled = True
        Else
          button1.enabled = False
        End If
      End Sub
    </SCRIPT>

Here is the same example using Tcl:

    <INPUT name="edit1" size="50">
    <SCRIPT type="text/tcl">
      proc edit1_changed {} {
        if {[edit value] == abc} {
          button1 enable 1
        } else {
          button1 enable 0
        }
      }
      edit1 onChange edit1_changed
    </SCRIPT>

Here is a JavaScript example for event binding within a script. First, here's a simple click handler:

    
<BUTTON type="button" name="mybutton" value="10">
<SCRIPT type="text/javascript">
      function my_onclick() {
         . . .
      }
    document.form.mybutton.onclick = my_onclick
 </SCRIPT>
 </BUTTON>

Here's a more interesting window handler:

    
<SCRIPT type="text/javascript">
      function my_onload() {
         . . .
      }

      var win = window.open("some/other/URL")
      if (win) win.onload = my_onload
</SCRIPT>

In Tcl this looks like:

 <SCRIPT type="text/tcl">
     proc my_onload {} {
       . . .
     }
     set win [window open "some/other/URL"]
     if {$win != ""} {
         $win onload my_onload
     }
 </SCRIPT>

Note that "document.write" or equivalent statements in intrinsic event handlers create and write to a new document rather than modifying the current one.

Parsing of intrinsic event scripts 

The script attributes for intrinsic events are defined as CDATA. The SGML processing of CDATA attribute values requires that (1) entity replacement occur within the attribute value; and (2) that the attribute value be delimited by matching pairs of double quotes (") or single quotes (').

Given these lexical restrictions, the delimiters ('), ("), "&", and "&#" may not occur freely in the value of a script attribute. To resolve this issue, we recommend that script event handler attributes always use (") delimiters and that occurrences of (") and "&" inside an event handler attribute be written as follows:

    '"'  should be written as "&quot;" or as "&#34;"
    '&'  should be written as "&amp;"  or as "&#38;"

Thus, for example, one could write:

 <INPUT name="num" value="0"
 onChange="if (compare(this.value, &quot;help&quot;)) {gethelp()}">

SGML permits (') to be included in attribute strings quoted by ("), and vice versa. The following is therefore correct:

"this is 'fine'" and 'so is "this"'

Dynamic modification of documents 

Scripts that are executed when a document is loaded may be able to modify the document's contents dynamically. The ability to do so depends on the scripting language itself (e.g., the "document.write" statement in the HTML object model supported by some vendors).

The dynamic modification of a document may be modeled as follows:

  1. All SCRIPT elements are evaluated in order as the document is loaded.
  2. All script constructs within a given SCRIPT element that generate SGML CDATA are evaluted. Their combined generated text is inserted in the document in place of the SCRIPT element.
  3. The generated CDATA is re-evaluated.

HTML documents are constrained to conform to the HTML DTD both before and after processing any SCRIPT elements.

The following example illustrates how scripts may modify a document dynamically. The following script:

 <TITLE>Test Document</TITLE>
 <SCRIPT type="text/javascript">
     document.write("<p><b>Hello World!<\/b>")
 </SCRIPT>

Has the same effect as this HTML markup:

 <TITLE>Test Document</TITLE>
 <P><B>Hello World!</B>

Designing documents for user agents that don't support scripting 

The following sections discuss issues about lack of support for scripting that authors should also consider when designing good HTML documents.

The NOSCRIPT element 

<!ELEMENT NOSCRIPT - - (%block)>

Start tag: required, End tag: required

The NOSCRIPT element allows authors to provide alternate content when a script is not executed. The content of a NOSCRIPT element should only rendered by a script-aware user agent in the following cases:

User agents that do not support client-side scripts must render this element's contents.

In the following example, a user agent that executes the SCRIPT will include some dynamically created data in the document. If the user agent doesn't support scripts, the user may still retrieve the data through a link.

<SCRIPT type="text/tcl">
 ...some Tcl script to insert data...
</SCRIPT>
<NOSCRIPT>
 <P>To access the data, click <A href="http://someplace.com/data">here.</A>
</NOSCRIPT>

Commenting out scripts 

User agents that don't recognize the SCRIPT element will likely render that element's contents as text. Some scripting engines, including those for languages JavaScript, VBScript, and Tcl allow the script statements to be enclosed in an SGML comment. User agents that don't recognize the SCRIPT element will thus ignore the comment while smart scripting engines will understand that the script in comments should be executed.

Another solution to the problem is to keep scripts in external documents and refer to them with the src attribute.

Commenting scripts in JavaScript
The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets "//" as starting a comment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.

<SCRIPT type="text/javascript">
<!--  to hide script contents from old browsers
  function square(i) {
    document.write("The call passed ", i ," to the function.","<BR>")
    return i * i
  }
  document.write("The function returned ",square(5),".")
// end hiding contents from old browsers  -->
</SCRIPT>

Commenting scripts in VBScript
In VBScript, a single quote character causes the rest of the current line to be treated as a comment. It can therefore be used to hide the string "-->" from VBScript, for instance:

   <SCRIPT type="text/vbscript">
     <!--
       Sub foo()
        ...
       End Sub
     ' -->
    </SCRIPT>

Commenting scripts in TCL
In Tcl, the "#" character comments out the rest of the line:

<SCRIPT type="text/tcl">
<!--  to hide script contents from old browsers
  proc square {i} {
    document write "The call passed $i to the function.<BR>"
    return [expr $i * $i]
  }
  document write "The function returned [square 5]."
# end hiding contents from old browsers  -->
</SCRIPT>

Note: Some browsers close comments on the first ">" character, so to hide script content from such browsers, you can transpose operands for relational and shift operators (e.g., use "y < x" rather than "x > y") or use scripting language-dependent escapes for ">".