Incorporating JavaScript into your HTML pages

Method 1: The SCRIPT tag

Including scripts in HTML is simple. Most scripts are contained inside a <SCRIPT> container tag. In other words, on opening <SCRIPT> tag starts the script and a closing </SCRIPT> tag ends it:

<SCRIPT TYPE="text/javascript">

/***** Beginning of JavaScript Program ******/

document.write("This document last modified on: ");
document.write(document.lastModified);

/***** End of JavaScript Program ******/

</SCRIPT>

Demo of the code

This code runs as soon as the browsers reads it. On the document it displays the message: This document last modified on: (Date of the Document last modification)

Where can you put a script? Anywhere in the <HEAD> or <BODY> of your HTML document. You'll learn as we progress that there are preferred locations for certain scripts, depending on what you are trying to accomplish. Note that you can put multiple scripts in your page.

Method 2: Placing JavaScripts within HTML tags

JavaScript code in a <SCRIPT> is executed once, when the HTML file that contains it is read into the web browser. A program that uses only this sort of static script cannot respond dynamically to the user. More dynamic programs define Event Handlers that are automatically invoked by the web browser when certain events occur - for example, when the user clicks on a button within a form. Because events in client-side JavaScript originate form HTML objects (like buttons), Event Handlers are defined as attributes of those objects.

In order to define JavaScript event handlers as part of HTML object definitions, JavaScript extends HTML by adding event handler attributes to various HTML tags. The <SCRIPT> tag can take optional attributes which determines how the JavaScript script in question is incorporated into the HTML file.

<INPUT TYPE="button" NAME="AlertButton" VALUE="Click here"
  onClick="alert('You just clicked the button')">

  • Demo of the above code
  • Previous Demo (highlights how JavaScript code can be "embedded" within HTML instead of being "separated" from HTML by having the code placed within the SCRIPT tags, which is the preferred method)

The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements you can write entire JavaScripts in one line. You can fit an entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.

Here the "script" is inside the <INPUT> tag. When you click the button, the "script" that appears after onClick, the alert() function, runs.

An "onMouseOver" example with the script within an HTML tag.

An example illustrating Methods 1 & 2 simultaneously.

Modular Event Handlers

Which of these is easier to read?

Explicit Event Handler

<INPUT
  TYPE="button"
  NAME="
click1"
  VALUE="Click me!"
  onClick="total += 50;
  tax = calcTax(total);
  document.priceform.total.value = total + tax;
">

Modular Event Handler

<INPUT
  TYPE="button"
  NAME="
click1"
  VALUE="Click me!"
  onClick="subTotal();">

At first this may seem convenient, but remember the KISS principle. What if you had 10 buttons or onMouseOver all using the same "event_handler_code" . If you had to make a change in the "event_handler_code" you would to have to make the change in 10 different places. Not a good way of doing something. Of course, this example assumes that the function subTotal() has been defined somewhere earlier in the page, such as embedded into the <HEAD> section or included via an external .js file which is discussed below. That's why we want to segregate scripts from HTML.

Attributes for the <SCRIPT> tag

ATTRIBUTE

DESCRIPTION

TYPE <SCRIPT TYPE="text/javascript">

This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type ("text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

LANGUAGE <SCRIPT LANGUAGE="JavaScript">

Indicates the language used in the script
(ie, JavaScript, JavaScript1.2, PerlScript, PHP, or VBScript)
This attribute has been deprecated. It was used to select other programming languages and specific versions of JavaScript. The values are not case sensitive.

NOTE: You don't need it. Don't use it.

DEFER By adding a defer attribute to your <SCRIPT DEFER="defer"> tag you are telling the browser that it can wait until it's done setting up the rest of the page before doing anything with the JavaScript block.

The problem with JavaScript is that when the browser is loading the page, whenever it comes across a <SCRIPT> tag, it stops, it loads the external script (if there is one), it evaluates the script, and it runs it before returning to the task of rendering the web page. This can impact page performance, making your site sluggish and slow-to-load, especially if you have multiple script blocks in your page.

NOTE: It is not universally supported.

SRC URL for a file containing the JavaScript source code. The file should have the extension .js.
The SRC attribute is optional. If it is present, then its value is a URL which identifies a file with extension .js. The loading and processing of the page pauses while the browser fetches, compiles, and executes the file.

NOTE: The content between the <SCRIPT SRC="URL"> and the </SCRIPT> should be blank.

Using External Files for JavaScript Programs

Including JavaScript programs directly in the HTML files can be convenient for small scripts and basic HTML pages, it can quickly get out of hand when pages require long and complex scripts or when the code and information is used throughout the website.

To make development and maintenance of HTML files and JavaScript scripts easier, the JavaScript specification includes the option of keeping your JavaScript in separate files and using the SRC attribute of the <SCRIPT> tag to include the JavaScript program in an HTML file

<SCRIPT TYPE="text/javascript" SRC="menu.js">

Your external script can contain any code you like, but it usually contains functions. Functions provide the modularity we seek in a programming architecture. The format of the .js file is simply the naked script with no HTML tags present. For example, consider this page made up of two files: one is the HTML source and the other is the JavaScript source.

eshop.htm

<HTML>
<HEAD>
<TITLE>E-Shop</TITLE>

<SCRIPT SRC="eshop.js"></SCRIPT>

</HEAD>

<BODY>
...etc...
</BODY>
</HTML>

eshop.js

function calcShipping(weight, state) {
     etc...
}

function calcTax(price, state) {
     etc...
}

Now you can see why external files allow for the possibility of creating portable functions. Imagine that you authored the calcShipping() function. Suppose it only required two incoming parameters, shipment weight and the destination state. The function itself then did all the dirty work -- translating the state abbreviation into a shipping zone and calculating the rate based on some representation of the shipping rate chart which you've built into the function. Once done the function simply returns a number reflecting the cost. As long as this function is coded portably; that is, relies only on internal local variables to do the work, you could distribute this function to anyone who wanted the ability to calculate shipping rates.

In fact, others wouldn't even need to copy the function from you. They could simply link to it on your server, should you be in such a generous mood:

<SCRIPT SRC="http://sislands.com/shopping/calcShipping.js">

Such a setup would be highly modular and portable -- if you had to change the rate table, you simply modify this function and every site which links to it will automatically reflect the new rates. Even if you are not ready to distribute your modular functions globally, this type of portability is useful even within your own site, since any page on your site can easily access common functions. And changes to these functions are immediately reflected on every page which uses them.

From a people perspective, the JavaScript guru of your team can play with calcShipping() all day without needing to see any of the HTML -- and vice versa for your HTML designers.

While the SRC attribute goes a long way to helping segregate programming language from markup tags, it is no panacea. There remains one large, sticky problem, and those are Event Handlers.

Note: At the same time, though, this technique requires an additional server request and server access, which may be problematic on a slow server or across a slow connection to the Internet.

Drop down menu & menu.js

Check out the source for menu.htm, where is the script that contains goPage(this.form)? menu.js contains the function. Even the browser doesn't display the menu.js scripts and functions when you view the source, the menu.js scripts and functions are really stored in the browser's memory ready for use. If an individual wanted to view the "missing" scripts, all the individual would have to do is just download the file, in this particular case menu.js happens to be in the same directory.

Commenting:

Here a brief comment is included after each variable declaration to explain what the variable is and how it will be used.

These comments make it much easier to decipher what is happening later on in the program. Because variable declaration is done first, these comments are also all grouped together in one place that is easy for someone reading the code to refer back to.

// Commenting
// using C++ style

/*
Commenting
using
this style is from C
*/

var Num = 0; // Number entered from button
var Num1 = 0; // Number to perform operation on
var Num2 = 0; // Number to perform operation on
var Num3 = 0; // Results of operating on N1, N2
var NumSet1 = "false"; // Have we finished entering N1?
var NumStart2 = "false"; // Have we started entering N2?
var DecSet = "false"; // Are we using a decimal place?
var Op = ''; // Operation as entered by user
var DoOp = ''; // Operation as accepted by script

Command Blocks

To make a script easier to read make use of command blocks. The simple process of using indentations greatly improves readability and being able to follow the flow of a program. Commenting & Command Blocks will in the long run definitely help improve your scripting.

if (day == "Saturday" || day == "Sunday") {
     document.write("It’s the weekend!");
}
else {
     document.write("It’s not weekend!");
}