Movatterモバイル変換


[0]ホーム

URL:


 previous next  contents  elements  attributes  index

18Scripts

Contents

  1. Introduction to scripts
  2. Designing documents for user agents thatsupport scripting
    1. TheSCRIPTelement
    2. Specifying the scripting language
    3. Intrinsic events
    4. Dynamic modification ofdocuments
  3. Designing documents for user agents thatdon't support scripting
    1. TheNOSCRIPT element
    2. Hiding script data from useragents

18.1Introduction toscripts

A client-sidescript is a program that may accompany an HTMLdocument or be embedded directly in it. The program executes on the client'smachine when the document loads, or at some other time such as when a link isactivated. HTML's support for scripts is independent of the scripting language.

Scripts offer authors a means to extend HTML documents in highlyactive and interactive ways. For example:

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

Note. This specification includes more detailedinformation about scripting in sections onscript macros.

18.2 Designing documents for user agents that supportscripting

The following sections discuss issues that concern user agents that supportscripting.

18.2.1 TheSCRIPT element

<!ELEMENTSCRIPT - -%Script;          -- script statements --><!ATTLIST SCRIPTcharset%Charset;      #IMPLIED  -- char encoding of linked resource --type%ContentType;  #REQUIRED -- content type of script language --src%URI;          #IMPLIED  -- URI for an external script --defer       (defer)        #IMPLIED  -- UA may defer execution of script --  >

Start tag:required, End tag:required

Attribute definitions

src =uri[CT]
This attribute specifies the location of an external script.
type =content-type[CI]
This attribute specifies the scripting language of the element's contentsand overrides the default scripting language. The scripting language isspecified as a content type (e.g., "text/javascript"). Authors must supply avalue for this attribute. There is no default value for this attribute.
language =cdata[CI]
Deprecated. Thisattribute specifies the scripting language of the contents of this element. Itsvalue is an identifier for the language, but since these identifiers are notstandard, this attribute has beendeprecated in favor oftype.
defer[CI]
When set, this boolean attribute provides a hint to the user agent that thescript is not going to generate any document content (e.g., no "document.write"in javascript) and thus, the user agent can continue parsing andrendering.

Attributes defined elsewhere

TheSCRIPT element places a script within a document. This element mayappear any number of times in theHEAD orBODY of an HTML document.

The script may be defined within the contents of theSCRIPT element or in an external file. If thesrcattribute is not set, user agents must interpret the contents of the element asthe script. If thesrc has a URI value, user agents must ignore the element'scontents and retrieve the script via the URI. Note that thecharset attribute refers to thecharacterencoding of the script designated by thesrc attribute; it does notconcern the content of theSCRIPT element.

Scripts are evaluated byscript engines that must be known to auser agent.

Thesyntax of script data depends onthe scripting language.

18.2.2Specifying the scripting language

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

The default scriptinglanguage 

Authors should specify the default scripting language for all scripts in adocument by including the followingMETA declaration in theHEAD:

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

where "type" is acontent typenaming the scripting language. Examples of values include "text/tcl","text/javascript", "text/vbscript".

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

    Content-Script-Type: type

where "type" is again acontenttype naming the scripting language.

User agents should determine the default scripting language for a documentaccording to the following steps (highest to lowest priority):

  1. If anyMETA declarations specify the "Content-Script-Type",the last one in the character stream determines the default scriptinglanguage.
  2. Otherwise, if any HTTP headers specify the "Content-Script-Type", the lastone in the character stream determines the default scripting language.

Documents that do not specify default scripting language information andthat contain elements that specify anintrinsic eventscript are incorrect. User agents may still attempt to interpret incorrectlyspecified scripts but are not required to. Authoring tools should generatedefault scripting language information to help authors avoid creating incorrectdocuments.

Local declaration of a scriptinglanguage 

Thetype attribute must be specified for eachSCRIPT element instance in a document. The value of thetype attribute for aSCRIPT element overrides the defaultscripting language for that element.

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd"><HTML><HEAD><TITLE>A document with SCRIPT</TITLE><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 HTMLelements from a script 

Each scripting language has its own conventions for referring to HTMLobjects from within a script. This specification does not define a standardmechanism 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 whenidentifying an element: aname attribute takes precedence overanid if both are set. Otherwise, one or the other may be used.

18.2.3Intrinsic events

Note. Authors of HTML documents are advised thatchanges are likely to occur in the realm of intrinsic events (e.g., how scriptsare bound to events). Research in this realm is carried on by members of theW3C Document Object Model Working Group (see the W3C Web Site athttp://www.w3.org/ for more information).

Attribute definitions

onload =script[CT]
Theonload event occurs when the user agent finishes loading awindow or all frames within aFRAMESET. This attribute may beused withBODY andFRAMESET elements.
onunload =script[CT]
Theonunload event occurs when the user agent removes adocument from a window or frame. This attribute may be used withBODY andFRAMESET elements.
onclick =script[CT]
Theonclick event occurs when the pointing device button isclicked over an element. This attribute may be used with most elements.
ondblclick =script[CT]
Theondblclick event occurs when the pointing device button isdouble clicked over an element. This attribute may be used with mostelements.
onmousedown =script[CT]
Theonmousedown event occurs when the pointing device buttonis pressed over an element. This attribute may be used with most elements.
onmouseup =script[CT]
Theonmouseup event occurs when the pointing device button isreleased over an element. This attribute may be used with most elements.
onmouseover =script[CT]
Theonmouseover event occurs when the pointing device is movedonto an element. This attribute may be used with most elements.
onmousemove =script[CT]
Theonmousemove event occurs when the pointing device is movedwhile it is over an element. This attribute may be used with mostelements.
onmouseout =script[CT]
Theonmouseout event occurs when the pointing device is movedaway from an element. This attribute may be used with most elements.
onfocus =script[CT]
Theonfocus event occurs when an element receives focus either by thepointing device or by tabbing navigation. This attribute may be used with thefollowing elements:A,AREA,LABEL,INPUT,SELECT,TEXTAREA, andBUTTON.
onblur =script[CT]
Theonblur event occurs when an element loses focus either bythe pointing device or by tabbing navigation. It may be used with the sameelements asonfocus.
onkeypress =script[CT]
Theonkeypress event occurs when a key is pressed and releasedover an element. This attribute may be used with most elements.
onkeydown =script[CT]
Theonkeydown event occurs when a key is pressed down over anelement. This attribute may be used with most elements.
onkeyup =script[CT]
Theonkeyup event occurs when a key is released over anelement. This attribute may be used with most elements.
onsubmit =script[CT]
Theonsubmit event occurs when a form is submitted. It onlyapplies to theFORM element.
onreset =script[CT]
Theonreset event occurs when a form is reset. It only appliesto theFORM element.
onselect =script[CT]
Theonselect event occurs when a user selects some text in atext field. This attribute may be used with theINPUT andTEXTAREA elements.
onchange =script[CT]
Theonchange event occurs when a control loses the input focusand its value has been modified since gaining focus. This attributeapplies to the following elements:INPUT,SELECT, andTEXTAREA.

It is possible to associate an action with a certain number of events thatoccur 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 wheneverthe event occurs for that element. Thesyntax of script data depends on the scripting language.

Control elements such asINPUT,SELECT,BUTTON,TEXTAREA, andLABEL all respond to certain intrinsic events. Whenthese elements do not appear within a form, they may be used to augment thegraphical user interface of the document.

For instance, authors may want to include press buttons in their documentsthat do not submit a form but still communicate with a server when they areactivated.

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

In the following example, userName is a required text field. When a userattempts to leave the field, theonblur event calls a JavaScriptfunction 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/URI")      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/URI"]     if {$win != ""} {         $win onload my_onload     } </SCRIPT>

Note that "document.write" or equivalent statements in intrinsic eventhandlers create and write to a new document rather than modifying the currentone.

18.2.4Dynamic modification of documents

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

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

  1. AllSCRIPT elements are evaluated in order as the document isloaded.
  2. All script constructs within a givenSCRIPT element that generate SGMLCDATA are evaluated. Their combined generated text is inserted in the documentin place of theSCRIPT element.
  3. The generated CDATA is re-evaluated.

HTML documents are constrained to conform to the HTML DTD both before andafter processing anySCRIPT elements.

The following example illustrates how scripts may modify a documentdynamically. 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>

18.3Designing documents for user agents thatdon't support scripting

The following sections discuss how authors may create documents that workfor user agents that don't support scripting.

18.3.1 TheNOSCRIPT element

<!ELEMENTNOSCRIPT - - (%block;)+  -- alternate content container for non script-based rendering --><!ATTLIST NOSCRIPT%attrs;                              --%coreattrs,%i18n,%events --  >

Start tag:required, End tag:required

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

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

In the following example, a user agent that executes theSCRIPTwill include some dynamically created data in the document. If the user agentdoesn't support scripts, the user may still retrieve the data through alink.

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

18.3.2Hiding script data from useragents

User agents that don't recognize theSCRIPT element will likely renderthat element's contents as text. Some scripting engines, including those forlanguages JavaScript, VBScript, and Tcl allow the script statements to beenclosed in an SGML comment. User agents that don't recognize theSCRIPTelement will thus ignore the comment while smart scripting engines willunderstand that the script in comments should be executed.

Another solution to the problem is to keep scripts in external documents andrefer to them with thesrc attribute.

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

<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 tobe 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 transposeoperands for relational and shift operators (e.g., use "y < x" rather than"x > y") or use scripting language-dependent escapes for ">".


previous  next  contents  elements  attributes  index

[8]ページ先頭

©2009-2025 Movatter.jp