• No results found

Prototypes and Inheritance (The Function Object)

In document Javascript Book (Page 27-125)

Adding JavaScript to a Web Page

When JavaScript was first introduced to web pages, Netscape needed to find some mechanism that allowed JavaScript to be added to a web page without causing adverse effects in other browsers. After much debate, it was finally settled on to incorporate the <script/> element, which was later added to the HTML specification.

tHe <Script/> eLement

The primary means of adding JavaScript to a web page is by using the <script/> element. This element, introduced by Netscape, became part of the HTML 3.2 specification as a placeholder for a transition to HTML 4.01, in which the element was fleshed out and given the following attributes:

src: Optional. Specifies an external script file to be executed.

type: Required. Specifies the language used in the <script/> element’s contents, and a value of "text/javascript" is typically used. Even though this attribute is required by the HTML specification, all browsers assume the language is JavaScript if this attri-bute is omitted.

language: Deprecated. This attribute specifies the language used in the <script/>

element’s contents. This attribute is no longer used, as type has replaced it.

defer: Optional. A Boolean (true or false) value that tells the browser whether to wait to execute any code within the <script/> element until after the browser loads the entire HTML document.

charset: Optional. The character encoding of the external code file specified by the src attribute. This attribute is rarely used.

1

4LeSSon 1 Adding JAvAScript to A Web pAge

There are two ways to use <script/> elements: either by embedding JavaScript code directly into the page, in which case it is referred to as inline code, or by using the src attribute to refer to that external file.

To add inline code to a web page, place the code between the opening and closing tags, as the follow-ing code shows:

Don’t worry about the code just yet — you’ll learn what this code does in due time. Even though browsers automatically assume that code within a <script/> element is JavaScript, it is considered good practice to include the type attribute. The browser stops loading the rest of the page when it encounters a <script/> element; it loads the code and interprets it before processing the rest of the HTML page.

It’s important to note that inline code blocks, as shown in the previous code sample, should be included in a CDATA block in XHTML documents. Failing to do so does not currently result in an error in the browser. In fact, all major browsers still load the JavaScript and execute it normally. However, there is no guarantee that future browsers will behave as today’s browsers do. So, if you use XHTML, future-proof your inline script by encapsulating it in a CDATA section, like this:

<script type="text/javascript">

Adding an external JavaScript file to the page incorporates the src attribute. It’s possible to cut the JavaScript code from the previous example, without the <script> tags, and paste it into another file. Then, by using the src attribute, the page can reference the external JavaScript file like this:

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

This <script/> element references an external JavaScript file called sample.js. Using the .js extension is a convention nearly all JavaScript developers use. It does not matter how the file is named — the browser will download it and interpret the file’s contents as JavaScript code.

Just as with inline code, the browser halts processing of the HTML page when it encounters the

<script> tag, but it also has to download the file before it begins interpreting it. After the browser loads the JavaScript from the external file, it resumes processing the HTML page.

The <script/> Element ❘ 5

Choosing whether to use inline or external scripts is ultimately up to you. However, the majority of developers use external JavaScript files for the following reasons:

External scripts are much easier to maintain than inline scripts, especially if you use the same code in several pages. Imagine having to edit multiple HTML pages to make identical changes to blocks of inline code. That would certainly be a time-consuming task. With an external file, you simply make changes to one file.

External scripts are cached by the browser, just as images and style sheets are. The browser down-loads the script file once and uses it for subsequent page requests as long as the script file hasn’t changed. This grants a certain performance gain in that the browser doesn’t have to download the same code over and over again, whereas it does if the code is embedded in the HTML page.

How and where <script/> elements are placed in the page do matter — they are loaded and inter-preted in the order in which they’re placed in the page.

tag placement

The <script/> element is one of the few elements that can go almost anywhere in an HTML page:

it can go within the <head/> element or the <body/> element. The more traditional place is within the <head/> element, along with the <style/> and <link/> elements. The following HTML demonstrates this:

<html>

<head>

<title>Sample Page</title>

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

</head>

<body>

</body>

</html>

While this keeps resources for the HTML page in one place within the document, remember that the browser halts all processing of the HTML document once it encounters a <script/> element, in order to download and load the script that it references. So placing <script/> elements at the top of the document has the side effect of delaying the browser from loading the page’s content. To users, this is a performance issue, as they see a blank web page while the browser downloads and loads the JavaScript.

Because of this, it’s becoming a best practice to place all <script> tags just before the closing

<body> tag, like this:

<html>

<head>

<title>Sample Page</title>

</head>

<body>

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

</body>

</html>

6LeSSon 1 Adding JAvAScript to A Web pAge

This way, the browser loads and renders the entire page before loading JavaScript code. Even though the net download time is the same regardless of the <script> tags’ placement, the user sees their requested web page sooner and perceives a faster web page.

try it

In this lesson, you add an external JavaScript file to a web page.

Lesson requirements

For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft’s free Visual Web Developer Express (www.microsoft.com/express/web/) or Web Matrix (www.asp.net/webmatrix/).

Mac OS X users can use TextMate, which comes as part of OS X, or download a trial for Coda (www.panic.com/coda/). Linux users can use the built-in VIM.

You also need a modern web browser. Choose any of the following:

Internet Explorer 8+

Google Chrome

Firefox 3.5+

Apple Safari 4+

Opera 10+

Create a folder somewhere in your file system called JS24Hour, and create a subfolder called Lesson01. Store the files you create in this lesson in the Lesson01 folder you created.

Step-by-Step

Add an external JavaScript file to a web page by following these steps:

1 .

Open your text editor and type the following JavaScript code:

function inlineScript() {

var message = "Hello, World!";

alert(message);

}

inlineScript();

2 .

Save the file as lesson01_sample01.js.

3 .

Open another instance of your text editor and type the following HTML:

<html>

<head>

<title>Sample Page</title>

</head>

Try It ❘ 7

<body>

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

</body>

</html>

4 .

Save this file as lesson01_sample01.html, and make sure you save it in the same location as lesson01_sample.js.

5 .

Open the HTML file in your web browser by double-clicking the file. You should see an alert box saying “Hello, World!” when the browser loads the page.

Please select Lesson 1 on the DVD to view the video that accompanies this les-son. You can also download the sample code for all lessons from the book’s website at www.wrox.com.

Variables and JavaScript Syntax

In the midst of teaching you how and where you add script to your pages, the previous lesson introduced the following simple script:

function inlineScript() {

var message = "Hello, World!";

alert(message);

}

inlineScript();

To fully understand what this code does, it’s important to know the basics of the JavaScript language. The core of any language is its syntax — a set of rules that dictate how certain pieces of the language fit together. Think of a spoken language and how difficult it would be to communicate with others if that language did not have a set of rules that defined how words are arranged into complete and understandable sentences. The same is applicable to program-ming languages. In the case of JavaScript, the browser wouldn’t know what to do with your code if it weren’t for the rules set forth by the language specifications. Syntax defines how very small pieces of code fit together in order to perform some kind of work.

This lesson focuses on the syntax of one line of code in the listing at the top of the page — the variable declaration:

var message = "Hello, World!";

In this lesson, you learn about variables and the syntax required to make them.

variaBLeS

Developers write programs to make working with data easier. Large amounts of data are typically stored outside the program, via the file system or a database, but many times that data is brought into the application and stored in the computer’s memory. Because of this, all

2

10LeSSon 2 vAriAbleS And JAvAScript SyntAx

programming languages need some way to access the data stored in memory in order to perform work on it.

Variables are parts of a programming language that grant programmers the ability to store and retrieve data stored in memory. You can think of a variable as a box — the box is empty when you create the variable, and the box is full when you assign that variable to hold data.

Some languages are very strict as to what type of data you can put in a particular box. These types of languages are called strongly-typed languages. For example, some languages have boxes for num-bers and numnum-bers only — trying to put pieces of text in a box for numnum-bers results in an error.

JavaScript is not one of these strongly-typed languages. Instead, it is a loosely-typed language — it sees a variable as a box that can hold any type of data at any given time. That box may grow or shrink to accommodate the data you put into it, but it does not discriminate between what types of data can fit in the box. This means that a variable can contain a text value at one time, and a num-ber value at another.

Defining a variable in JavaScript requires the use of a variable declaration statement. A statement is a small piece of code that performs some kind of action. Any given program is made up of one or more statements in a specific sequence. The following code shows a variable declaration statement:

var myVariable;

Most JavaScript statements end with a semicolon, as shown in this code. But it is also valid to omit them, as shown in the following code:

var myVariable

However, omitting the semicolon is considered a bad programming practice and is strongly discour-aged. This code is considered bad code.

Variable declarations begin with the var keyword, a word reserved by the language for a specific use. The var keyword is used specifically for declaring variables. Following the var keyword is the variable’s identifier, or name. Identifiers are made up of one or more characters, and they must fol-low these rules:

An identifier’s first character must be a letter, an underscore, or a dollar sign. Many JavaScript libraries make extensive use of the dollar sign. So, it is suggested that you avoid using it.

All other characters can be letters, whole decimal numbers (0–9), underscores, or dollar signs.

An identifier cannot be the same as a keyword or reserved word (more on these later).

An identifier should briefly describe what the variable contains.

It is important to note the casing of each letter in the variable’s identifier. JavaScript is a case-sensitive language: It distinguishes between uppercase and lowercase letters. The previous identifier,

Variables ❘ 11

myVariable, is not the same as myvariable, Myvariable, mYVariable, or any such variation. It’s important to always be aware of an identifier’s case, as failing to do so is a very common cause of errors.

The myVariable identifier uses what’s called camel-case. This means that the first letter of the identi-fier is lowercase, and each word in the identiidenti-fier starts with an uppercase letter. Camel-casing isn’t a requirement of JavaScript, but most of JavaScript’s built-in identifiers use camel-case. As a pro-grammer, it’s a good idea to follow the conventions of the language you’re using. In the case of JavaScript, that means following the camel-casing guidelines when naming your own identifiers.

The variable declaration statement in the previous code doesn’t contain any data. It has been declared, but it has not been initialized, or assigned a value. To assign data to a variable, use the equals sign (=), also known as the assignment operator, to assign a value to the variable. An operator is a symbol or keyword that takes one or more operands as input and performs an action on those operands.

var myVariable;

myVariable = "some text";

This code declares and initializes myVariable in two separate statements. The first statement is a declaration statement (declaring the variable with the var keyword), and the second statement is an initialization statement (giving the variable an initial value). Notice there is no var keyword used in the initialization line. The var keyword is used only for declaring variables. Once a variable is declared, it is no longer necessary to use var for that variable.

The operands in an assignment operation, as shown in the initialization statement in the previous example, are on both sides of the assignment operator (the equals sign). The operand on the right is an expression or value that is assigned to the operand on the left (the variable).

Using two statements, as in the previous example, is sometimes necessary, as the data for a variable may not exist at the time the variable is declared. However, a variable can be declared and initial-ized in one statement. The following code shows this:

var myVariable = "some text";

Using one statement is preferred, as it is easier to read and results in a smaller file size.

A variable’s value can be overwritten with another value at any time. Using the myVariable from the previous example, the following code overwrites the "some text" value with that of a number:

myVariable = 100;

The variable now contains the number 100. There is no limit to the number of times a variable can be overwritten.

A variable can also be assigned the value contained in another variable. The following line creates a new variable called myVariable2, and it is initialized with the value contained within myVariable:

var myVariable2 = myVariable;

So now the myVariable2 variable contains a value of 100. Even though these two variables con-tain the same value, and it may look as if they are linked, they are, in fact, independent from one

12LeSSon 2 vAriAbleS And JAvAScript SyntAx

another. In other words, modifying the value contained in myVariable has no effect on the data in myVariable2. This variable independence comes from the fact that numbers are a primitive data type in JavaScript.

primitive data types in JavaScript

A data type is a type of value represented in a programming language, such as numbers, text, and true/false values (among other things). Primitive data types are the basic types of data provided by a programming language. They are the building blocks for more complex data types.

JavaScript has five primitive data types. They are:

JavaScript’s primitive data types hold only one value at a time and are immutable. This means that once a primitive value is created, it cannot be changed. Instead, the variable’s original value must be destroyed and replaced with a new value. A primitive variable directly contains the value it is assigned. Assigning a variable the value of a primitive data type copies the value of the second vari-able, and that copy is assigned to the first variable.

Consider the following code, which recreates the myVariable and myVariable2 variables:

var myVariable = 5,

myVariable2 = myVariable; // copies the number and assigns copy myVariable = 6; // destroys old number value and assigns new // number value in 2nd variable still intact

Before I discuss this code, you undoubtedly noticed some new syntax at the end of lines two, three, and four. These are comments. Comments are human-readable annotations in code. They are ignored by JavaScript and are meant to provide information to anyone reading the code. The types of com-ments presented in the previous code are single-line comcom-ments. They begin with two forward slashes (//), and anything after the slashes is considered a comment. Again, comments are completely ignored by JavaScript, but they give the reader insight about particular lines of code.

Something else you might have noticed is a comma separating the initialization of the myVariable and myVariable2 variables, along with the omission of the var keyword in the second line. The first two lines of this code initialize two variables in a single statement. These multiple variable initializa-tion statements begin with the var keyword, and each subsequent variable initialization is separated with a comma. You can initialize as many variables as you want within a single statement. Just start the statement with var, separate each initialization with a comma, and end the statement with a semicolon.

Variables ❘ 13

It does not matter if you initialize variables in one or multiple statements. It’s a personal preference. For the sake of clarity, this book opts to use multiple state-ments to initialize variables.

The first line of code initializes the myVariable variable as containing a value of 5. This value is of the Number data type. The second line of code initializes the myVariable2 variable by copying the

The first line of code initializes the myVariable variable as containing a value of 5. This value is of the Number data type. The second line of code initializes the myVariable2 variable by copying the

In document Javascript Book (Page 27-125)

Related documents