Previous Section
Home
Next Section


Including Scripts in an XHTML Document

As suggested by the introductory examples, the primary way to include scripts¾written in any language¾in a Web page is through the use of the <script> tag. There are actually four ways to include script code in a document:

The syntax of each of these approaches is presented in the following sections with simple examples.

The <script> Tag

The script element is used to section off any script included directly within a Web page. Within the element should be scripting statements in the particular language used. Any script code is executed by the browser and the results are then output to the document. If the output contains markup, CSS, or even more script code, it is then parsed further by the browser. For example, consider the short markup and script fragment here that might be found in a document body:

<h2>Before the JavaScript</h2>
<script type="text/javascript">
   document.write("Hello world from <b>Javascript</b>.");
</script>
<h2>After the Javascript</h2>

This would produce a heading of text, the short greeting from JavaScript, and then the second heading. Notice that the text generated by JavaScript includes the <b> tag, which then would be interpreted by the browser before final display. A more telling example shows how the browser executes a few statements at a time:

<h2>Heading 1</h2>
<script type="text/javascript">
   alert("Script 1");
</script>
<h2>Heading 2</h2>
<script type="text/javascript">
   alert("Script 2");
</script>
<h2>Heading 3</h2>
<script type="text/javascript">
   alert("Script 3");
</script>
<h2>Done!</h2>

In this example, the browser will output a statement and then an alert allowing you to witness the incremental display and parse of the page.

The <script> tag can occur in either the head or the body elements numerous times. Because a document is read from top to bottom, many scripts will be found in the head; these must be read before the page is loaded. Programmers will find scripts in the head of the document useful to declare and initialize variables and set up functions for later use. For example, the following example sets up a function that can be triggered later on in the document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript Example</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">
 function greet()
  {
    alert("Hello user! Welcome to JavaScript.");
   }
</script>
</head>
<body>
 
  markup and JavaScript that may eventually trigger script
found in the head of the document
   
</body>
</html>

In this particular example, the script in the head is only a function definition. It won't necessarily be executed unless you call it down in the <body> of the document. Later on in the page, you could have a special script block such as

<script type="text/javascript">
   greet();
</script>

which could invoke the short script defined in the <head> of the document.

Hiding Script

When using script markup within a document, you may have to address what to do when a browser doesn't support scripting. Traditionally when a browser encounters an element it doesn't support it simply skips it and prints out the contents within the element as plain text. A non-JavaScript-aware browser encountering an example such as

<script type="text/javascript">
         alert("I am a script.");
</script>

literally would print alert("I am a script."); rather than running the script first. In order to avoid this undesirable situation, you should attempt to hide the script code from older browsers using comments, in a fashion similar to the technique for hiding style sheets. An example of commenting on JavaScript is shown here:

<script type="text/javascript">
<!--
alert("I am a script.");
//-->
</script>

Notice how the HTML comment starts the exclusion of JavaScript, but //--> is used to close the comment. This is because JavaScript interprets lines with // as comments and does not attempt to run --> as a command.

Note 

Other scripting languages such as VBScript may have different commenting styles for hiding the script code from older browsers.

XHTML has a slightly different issue with the script element. Given that XHTML is an XML-based language, many of the characters found in a JavaScript, such as > or &, have special meaning so there could be trouble with the previous approach. According to the strict XHTML specification, you also are supposed to hide the contents of the script from the XHTML-enforcing browser using the following technique:

<script type="text/javascript">
<![CDATA[
    ..script here ..
]]>
</script>

Of course, this approach does not work in any but the strictest XML enforcing browsers, so authors will have to instead use linked scripts, traditional comment blocks, or simply ignore the problem. This is not the optimal solution to say the least, but it is typical of the compromises often made in Web development.

<noscript>

Like other elements that reference technologies beyond basic markup, the script element supports a special element to deal with browsers that don't execute a script. The <noscript> tag is used to enclose alternative text and markup for browsers that don't interpret a script. Furthermore, users can turn off support for a scripting language in their browsers. The <noscript> content renders onscreen, as shown in the following example, if the user has turned off scripting support or is using a browser that doesn't understand JavaScript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>JavaScript and noscript</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<script type="text/javascript">
<!--
 document.write('JavaScript is on');
//-->
</script>
<noscript>
<b>This page requires JavaScript. Please turn on JavaScript if you
   have it and reload this page!</b>
</noscript>
</body>
</html>
Note 

It is possible to turn off JavaScript support in a browser rather easily by setting your preferences. This browser modification is performed by users primarily for security reasons, because there are many privacy exploits related to JavaScript usage.

Specifying the Scripting Language

By default, most browsers assume that the script language being used is JavaScript. As the previous examples have shown, the type attribute is used to indicate the MIME type of the script to run; for example, text/javascript. However, this indication of scripting dialect, while a specified standard, might not provide the flexibility provided by the nonstandard language attribute. For example, consider that not all versions of JavaScript support the same features. The language attribute can be used to indicate the version of JavaScript being used. The attribute can be set to "JavaScript1.1" or "JavaScript1.2" rather than simply" JavaScript". Only browsers that understand the particular dialect of JavaScript will execute the enclosed script code. To deal with this, you can make a fall-back situation with multiple versions of similar code, as shown here:

<script language="JavaScript">
 Traditional JavaScript version
</script>
   
<script language="JavaScript1.1">
 JavaScript 1.1 version
</script>
   
<script language="JavaScript1.2">
  JavaScript1.2 version
</script>
   
<script language="JavaScript1.5">
  JavaScript1.5 version
</script>

In the previous example, the browser will execute each script block in order and skip any versions of the language attribute it doesn't understand. This would allow the developer to put different versions of code in different blocks. One caveat to consider with the language attribute is that because a browser will ignore any element with any unknown language, a simple typo such as <script language="javascipt"> will cause the entire script to be skipped. Furthermore, while commonly used and more useful than the type attribute, markup using the language attribute will of course not validate.

Linked Scripts

While it is easy to put scripts directly in a document, it probably is better to separate them out in an external file and link to them, similar to linked style sheets. You can place the script code in a separate file and use the src attribute to specify the URL of the script to include. For example,

<script src="/scripts/myscript.js" type="text/javascript"></script>

loads a script called myscript.js, specified by the URL for the src attribute. The external file would contain only JavaScript and no HTML/XHTML markup, not even a <script> tag. For example, using the previous example, you would have

function greet()
{
    alert("Hello user! Welcome to JavaScript.");
}

in the file myscript.js.

One major advantage of external scripts is that a browser can cache the script file locally. If the same script code is used over and over again, the files that reference it require only another <script> tag and can reuse the cached copy. Considering how much script code is inserted in many pages, this could improve site efficiency. Furthermore, using an included script also keeps markup, script, and style elements separate.

Although external scripts seem the way to go, they do have problems. The most troubling issue has to do with load order. Given that each .js file is a separate request, some code may be downloaded and executed before related code is. This multirequest can lead to transitory network-related scripting errors, which can be very hard to pin down. There are other issues with compatibility with external scripts. Even today's modern browsers have occasional problems with certain constructs in external scripts and very old browser implementations of JavaScript—notably Netscape 2.0 and early versions of Internet Explorer 3.0—do not support external scripts at all. However, today these browser problems are rarely an issue, and linked scripts should be employed whenever possible.

Event Handler Attributes

Script code can also be added to XHTML documents through special attributes called event handlers. What are events? Events occur as the result of a user action or, potentially, an external event, such as a page loading. Examples of events include a user clicking a button, pressing a key, scrolling a window, or even simply moving the mouse around the screen. XHTML provides a way to bind a script to the occurrence of a particular event, through an event handler attribute. This is the name of the event, prefixed by the word "on": for example, onclick. The following code shows how the onclick event handler attribute is used to bind a script to a button click occurrence:

<form action="#">
<input type="button" onclick="alert('This is JavaScript');"
       value="Press Me" />
</form>

Under standard HTML and XHTML, event handler attributes can be added to quite a number of elements, some of which may be unexpected. Consider the following:

<p onclick="alert('Under HTML 4 and XHTML you can!');">Can you click me?</p>

The core event model introduced in HTML 4 and supported in XHTML includes onclick, ondblclick, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, and onmouseup. These core events are defined for nearly all markup elements in which the element is displayed onscreen. The specific elements and their events are discussed in Appendix A. Be careful, however, because some browsers, particularly slightly older ones, do not support core events on every element. In reality, it often doesn't make sense to associate events with some elements anyway.

In addition to the core events, certain elements have their own special events. For example, the body and frameset elements have an event for loading (onload) and unloading pages (onunload). In the case of the frameset element, the load and unload events don't fire until all the frames have been loaded or unloaded, respectively. The <form> tag also has two special events that typically are triggered when the user clicks the Submit or Reset button for a form. These events are onsubmit and onreset. For form text fields set with the <input> tag, you can catch the focus and blur events with onfocus and onblur. These events fire when the user accesses the field and moves on to another one. You also can watch for the select event with onselect, which is triggered when a user selects some text, as well as the change event (onchange), which is triggered when a form field's value changes and loses focus. Table 14-1 summarizes the main events supported by HTML and XHTML and their associated elements.

Table 14-1: Events Defined in HTML 4 and XHTML

Event Attribute

Event Description

Elements Allowed Under XHTML

onblur

A blur event occurs when a form field loses focus, typically meaning that the user has entered into another form field either typically by clicking the mouse on it, or by tabbing to it.

a
area
button
input
label
select
textarea

onchange

A change event signals both that the form field has lost user focus and that its value has been modified during its last access.

input
select
textarea

onclick

Indicates that the element has been clicked.

Most elements

ondblclick

Indicates that the element has been double-clicked.

Most elements

onfocus

The focus event describes when a form field has received focus, namely that it has been selected for manipulation or data entry.

a
area
button
input
label
select
textarea

onkeydown

Indicates that a key is being pressed down.

Most elements

onkeypress

Describes the event of a key being pressed and released.

Most elements

onkeyup

Indicates that a key is being released.

Most elements

onload

Indicates the event that occurs when a window or frame finishes loading a document.

body
frameset

onmousedown

Indicates the press of a mouse button.

Most elements

onmousemove

Indicates that the mouse has moved.

Most elements

onmouseout

Indicates that the mouse has moved away from an element.

Most elements

onmouseover

Indicates that the mouse has moved over an element.

Most elements

onmouseup

Indicates the release of a mouse button.

Most elements

onreset

Indicates that the form fields are to be cleared as indicated by the click of a Reset button.

form

onselect

Indicates the selection of text by the user, typically by highlighting the text.

input
textarea

onsubmit

Indicates a form submission by the clicking of a Submit button.

form

onunload

Indicates that the browser is leaving the current document and unloading it from the window or frame.

body
frameset

The following markup illustrates simple use of the core event attributes with form elements and links:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Core Events</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head>
<body onload='alert("Event demo loaded");'
      onunload='alert("Leaving demo");'>
   
<h1 align="center">Core Events</h1>
<form action="#" onreset='alert("Form reset");'
      onsubmit='alert("Form submit");return false;'>
   
<ul>
<li>onblur: <input type="text" value="Click into field and then leave"
                   size="40" onblur='alert("Lost focus");' />
<br /><br /></li>
   
<li>onclick: <input type="button" value="Click Me"
                    onclick='alert("Button click");' /><br /><br /></li>
   
<li>onchange: <input type="text" value="Change this text then leave"
                     size="40" onchange='alert("Changed");' />
<br /><br /></li>
   
<li>ondblclick: <input type="button" value="Double-click Me"
                       ondblclick='alert("Button double-clicked");' />
<br /><br /></li>
   
<li>onfocus: <input type="text" value="Click into field"
                    onfocus='alert("Gained focus");' /><br /><br /></li>
   
<li>onkeydown: <input type="text" 
                      value="Press key and release slowly here" size="40"
                      onkeydown='alert("Key down");' /><br /><br /></li>
   
<li>onkeypress: <input type="text" value="Type here" size="40"
                       onkeypress='alert("Key pressed");' />
<br /><br /></li>
   
<li>onkeyup: <input type="text" value="Type and release" size="40"
                    onkeyup='alert("Key up");' /><br /><br /></li>
   
<li>onload:   Alert presented on initial document load.<br /><br /></li>
   
<li>onmousedown: <input type="button" value="Click and hold"
                        onmousedown='alert("Mouse down");' />
<br /><br /></li>
   
<li>onmousemove: Move mouse over this
<a href="#" onmousemove='alert("Mouse moved");'>link</a><br /><br /></li>
   
<li>onmouseout: Position 
mouse <a href="#" onmouseout='alert("Mouse out");'>here</a> 
and now leave.<br /><br /></li>
   
<li>onmouseover: Position mouse over this
<a href=""onmouseover='alert("Mouse over");'>link</a><br /><br /></li>
   
<li>onmouseup: <input type="button" value="Click and release"
                      onmouseup='alert("Mouse up");' /><br /><br /></li>
   
<li>onreset: <input type="reset" value="Reset Demo" /><br /><br /></li>
   
<li>onselect: <input type="text" value="Select this text" size="40"
                     onselect='alert("Selected");' /><br /><br /></li>
   
<li>onsubmit: <input type="submit" value="Test Submit" /><br /><br /></li>
   
<li>onunload: Try to leave document by following this
<a href="http://www.yahoo.com">link</a>.<br /><br /></li>
   
</ul>
</form>
</body>
</html>

Whereas HTML and XHTML specifies numerous events, Netscape and Internet Explorer support many more events beyond the core set. A more detailed discussion of the various events unique to browsers can be found in Appendix A.

The javascript: URL

Most JavaScript-aware browsers introduced the use of a new URL style in the form of javascript:, which can be used with links. For example,

<a href="javascript:alert('Danger! JavaScript ahead!');">
Click for script</a>

creates a link that, when clicked, executes the specified JavaScript code. Although this pseudo-URL form is commonly used in many scripts, it does have a downside in that the link will not function at all when scripting is turned off. Designers should at minimum make sure to include a <noscript> tag to warn users of this situation or to avoid the use of pseudo- URL script triggers. A better solution would be to avoid using the javascript: pseudo-URL, as demonstrated here:

<a href="errors/noscript.html" 
   onclick="alert('Danger! JavaScript ahead!');return false;">
Click for script</a>

In this situation, notice that with the scripting on, the alert is displayed and then the link load is canceled by returning a false value. Some events such as link loads, right-clicks, and form submissions can be controlled by returning a value to the handler. You'll see this used later on with form validation. In this particular case, you see that by providing both an event handler approach and a set URL, you handle all user cases. With the scripting off, the link could be directed to send the user to an error page, as shown in the previous code listing, or to an alternative version of the content.



Previous Section
Home
Next Section