Chapter 1. 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 attribute 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.

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 following code shows:

<script type="text/javascript">
function inlineScript() {
    var message = "Hello, World!";
    alert(message);
}

inlineScript();
</script>

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">
<![CDATA[[
function inlineScript() {
    var message = "Hello, World!";
    alert(message);
}

inlineScript();
]]>
</script>

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.

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 downloads 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 interpreted 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>

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>
    <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.

Note

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

Step-by-Step
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.95.245