Trace: » research » creation » condensed_while » drawingapi » databases » notes » vectors » imagegallery » chapter1

Table of Contents

Chapter 1

Hello World

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Example 1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
<script type="text/javascript">
   var dt = Date(  );
 
   // say hello to the world
   var msg = 'Hello, World! Today is ' + dt;
   alert(msg);
</script>
</head>
<body onload="hello(  );">
</body>
</html>

JavaScript, unlike some other languages, is almost always embedded within the context of another language, such as HTML and XHTML (both of which are actual languages, though the moving parts may not be as obvious). By this I mean that there are restrictions in how the script is added to the page. You can’t just plop JS into the page wherever and however you want.

All these type values describe the MIME type of the content. MIME, or Multipurpose Internet Mail Extension, is a way to identify how the content is encoded (i.e., text), and what specific format it is (javascript). The concept arose with email, but spread to other Internet uses, such as designating the type of script in a script block.

By providing a MIME type, those browsers capable of processing the type do so, while other browsers skip over the section. This ensures that the script is accessed only by applications that can process it.

Earlier versions of the script tag took a language attribute, and this was used to designate the version of the language, as well as the type: javascript as compared to javascript 1.2. However, the use of language was deprecated in HTML 4.01, though it still shows in many JavaScript examples. And therein lies one of the earliest cross-browser techniques.

Returning to the script tag, other valid attributes for this tag are src, defer, and charset. The charset attribute defines the character encoding used with the script. Unless you need a different character encoding than what’s defined for the document, this usually isn’t set.

One attribute that can be quite useful is defer. If you set defer to a value of “defer,” it indicates to the browser that the script is not going to generate any document content, and the browser can continue processing the rest of the page’s content, returning to the script when the page has been processed and displayed:

<script type="text/javascript" defer="defer">
...no content being generated
</script>

Using this can help speed up page loading when you have a larger JavaScript block or include a larger JS library. The last attribute, src, has to do with loading such libraries, and we’ll explore it next.

Example 1-2. Embedding JavaScript into the document body

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>JavaScript Code Block Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
//<![CDATA[
 
var dt = Date(  );
var msg ='<h3>Hello, World! Today is ' + dt + '</h3>';
document.writeln(msg);
 
//]]>
</script>
</body>
</html>

Note in this example, rather than the alert function, the DOM document object is used to write directly to the page.

There are differing viewpoints on when JS should be included in the head and when in the body, but the following rules apply:

A good rule of thumb with script placement is to embed the script in the body only when the script creates web page contents as it’s loaded; otherwise, put it in the head element. This way, the page won’t be cluttered with script, and the script can always be found in one location on each page.

Hiding the Script

A CDATA section holds text that the XHTML processor doesn’t interpret.

The reason for the CDATA section is that XHTML processors interpret markup such as the header (H3) opening and closing tags, even when they’re contained within JavaScript strings. Though the page may display correctly, if you try to validate it without the CDATA, you will get validation errors.

JavaScript that is imported into the page using the SRC attribute is assumed to be compatible with XHTML and doesn’t require the CDATA section. Inline or embedded JS, though, should be delimited with CDATA, particularly if it’s included within the BODY element.

For most browsers, you’ll also need to hide the CDATA section opening and closing tags with JavaScript comments (//), or you’ll get a JavaScript error.

JavaScript Best Practice: The use of both the CDATA section and the JavaScript comments is important enough that these form the first of many JavaScript Best Practices that will be covered in this book.

When using an XHTML DOCTYPE, enclose inline or embedded JavaScript blocks in CDATA sections, which are then commented out using JavaScript comments. And always assume your web pages are XHTML, so always use CDATA.

Of course, the best way to keep your web pages uncluttered is to remove the JavaScript from the page entirely, through the use of JavaScript files. Many of this book’s examples are embedded into the page primarily to make them easier to create. However, the Mozilla Foundation recommends that all inline or embedded JavaScript be removed from a page and placed in separate JS files. Doing this prevents problems with validation and incorrect interpretation of text, regardless of whether the page is processed as HTML or XHTML.

JavaScript Best Practice: Place all blocks of JavaScript code within external JavaScript files.

JavaScript Files

To include a JavaScript library or script file in your web page, use this syntax:

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

The script element contains no content, but the closing tag is still required.

Browser Objects

The first example used the alert function to create a small pop-up window (usually called a dialog window) with the provided message. Though not specifically included in the text, the alert dialog is a function of the window objectthe top-most object in the Browser Object Model (BOM). The BOM is a basic set of objects implemented in most modern browsers.

The second example also used an object from the BOMthe document objectto write the message out to the page. The document, window, and all BOM objects are covered in Chapter 9.

The BOM is a variation of the DOM mentioned earlier, and it is sometimes referred to as DOM Version 0.

JavaScript Built-in Objects

Examples 1-1 and 1-2 also use two other built-in objects, though only one is used explicitly. The explicit object is date; it accesses today’s date. The second, implicit, object is string, which is the type of object that’s returned when the date function is called. In fact, the following are all comparable implementations of the same code:

var dt = String(Date(  ));
var dt = Date(  ).toString(  );

JavaScript User-Defined Functions

The global function and built-in object are used within the context of a user-defined function (UDF) in Example 1-1. The typical syntax for creating a UDF is:

               function functionname(params) {
...
}

The keyword function is followed by the function name and parentheses containing zero or more parameters (function arguments), followed by the function code contained within curly brackets. The function may or may not return a value. A user-defined function encapsulates a block of JavaScript for later or repeated processing.

Functions are technically another kind of a built-in JavaScript object. They look like statements, and you don’t need to worry much about the distinction until you’re building lots of them. However, they are objects, and they are complex enough and important enough to have their own chapter, Chapter 5.

Event Handlers

The onload attribute is what’s known as an event handler. This event handler, and others, are part of the underlying DOM that each browser provides. They can attach a function to an event so that when the event occurs, some code is processed.

There are several events that can be captured in various types of elements, each of which can then be assigned code to be implemented when the event occurs.

Adding an event handler directly to the element tag is one way to attach an event handler. A second technique occurs directly within JavaScript using a syntax such as the following:

<script type="text/javascript">
document.onload=hello(  );
 
function hello(  ) {
   var dt = Date(  );
   var msg = 'Hello, World! Today is ' + dt;
   alert(msg);
}
</script>

Mozilla has provided a good documentation set covering the Gecko engine (the underlying engine that implements JavaScript within browsers such as Camino and Firefox). The URL for the event handlers is here