JavaScript is a client-side scripting language that runs entirely
inside the web browser. To call it up, you place your JavaScript code
between opening <script>
and
closing </script>
HTML tags. A typical
HTML 4.01 “Hello World” document using JavaScript might look like Example 13-1.
<html> <head><title>Hello World</title></head> <body> <script type="text/javascript"> document.write("Hello World") </script> <noscript> Your browser doesn't support or has disabled JavaScript </noscript> </body> </html>
You may have seen web pages that use the HTML tag <script language="javascript">
, but that
usage has now been deprecated. This example uses the more recent and
preferred <script
type="text/javascript">
.
Within the <script>
tags is
a single line of JavaScript code that uses the JavaScript equivalent of
the PHP echo
or print
commands, document.write
. As you’d expect, it simply
outputs the supplied string to the current document, where it is
displayed.
You may have also noticed that, unlike with PHP, there is no
trailing semicolon (;
). This is because
a newline serves the same purpose as a semicolon in JavaScript. However,
if you wish to have more than one statement on a single line, you do need
to place a semicolon after each command except the last one. And of
course, if you wish, you can add a semicolon to the end of every statement
and your JavaScript will work fine.
The other thing to note in this example is the <noscript>
and </noscript>
pair of tags. These are used
when you wish to offer alternative HTML to users whose browsers do not
support JavaScript or who have it disabled. The use of these tags is up to
you—they are not required—but you really ought to use them, because it’s
usually not that difficult to provide static HTML alternatives to the
operations you provide using JavaScript. That said, the remaining examples
in this book will omit <noscript>
tags, because we’re focusing on what you can do with JavaScript, not what
you can do without it.
When Example 13-1 is loaded, a web browser with JavaScript enabled will output the following (see Figure 13-1):
Hello World
One with JavaScript disabled will display this (see Figure 13-2):
Your browser doesn't support or has disabled JavaScript
In addition to placing a script within the body of a document, you
can put it in the <head>
section, which is the ideal place if you wish to execute a script when a
page loads. If you place critical code and functions there, you can also
ensure that they are ready to use immediately by any other script
sections in the document that rely on them.
Another reason for placing a script in the document head is to
enable JavaScript to write things such as meta tags into the <head>
section, because the location of
your script is the part of the document it writes to by default.
If you need to support browsers that do not offer scripting, you
will need to use the HTML comment tags (<!--
and -->
) to prevent them from encountering
script code that they should not see. Example 13-2 shows how you add
them to your script code.
<html> <head><title>Hello World</title></head> <body> <script type="text/javascript"><!--
document.write("Hello World")// -->
</script> </body> </html>
Here, an opening HTML comment tag (<!--
) has been added directly after the
opening <script ...>
statement
and a closing comment tag (// -->
)
directly before the script is closed with </script>
.
The double forward slash (//
)
is used by JavaScript to indicate that the rest of the line is a
comment. It is there so that browsers that do
support JavaScript will ignore the following -->
, but non-JavaScript browsers will
ignore the preceding //
and act on
the -->
closing the HTML
comment.
Although the solution is a little convoluted, all you really need to remember is to use the two following lines to enclose your JavaScript when you wish to support very old or nonstandard browsers:
<script type="text/javascript"><!—
(Your JavaScript goes here...)
// --></script>
However, the use of these comments is unnecessary for any browser released over the past several years.
There are a couple of other scripting languages you should know about. These include Microsoft’s VBScript, which is based on the Visual Basic programming language, and Tcl, a rapid prototyping language. They are called up in a similar way to JavaScript, except they use types of text/vbscript and text/tcl, respectively. VBScript works only in Internet Explorer; use of it in other browsers requires a plug-in. Tcl always needs a plug-in. So, both should be considered nonstandard and neither is covered in this book.
In addition to writing JavaScript code directly in HTML documents, you can include files of JavaScript code either from your website or from anywhere on the Internet. The syntax for this is:
<script type="text/javascript" src="script.js"></script>
Or, to pull a file in from the Internet:
<script type="text/javascript" src="http://someserver.com/script.js"> </script>
As for the script files themselves, they must
not include any <script>
or </script>
tags, because they are
unnecessary: the browser already knows that a JavaScript file is being
loaded. Putting them in the JavaScript files will cause an error.
Including script files is the preferred way for you to use third-party JavaScript files on your website.
It is possible to leave out the type="text/javascript"
parameter; all modern
browsers default to assuming that the script contains JavaScript.
When learning JavaScript, it’s important to be able to track typing or other coding errors. Unlike PHP, which displays error messages in the browser, JavaScript error messages are handled differently, and in a way that changes according to the browser used. Table 13-1 lists how to access JavaScript error messages in each of the five most commonly used browsers.
Browser | How to access JavaScript error messages |
Apple Safari | Safari does not have an
Error Console enabled by default, but you can turn it on by
selecting Safari→Preferences→Advanced and checking the “Show Develop
menu in menu bar” box. Alternatively, you may prefer to use the
Firebug Lite JavaScript module, which many people find easier to
use: |
Google Chrome | Click the menu icon that looks like a page with a corner turned, then select Developer→JavaScript Console. You can also use the shortcut Ctrl-Shift-J on a PC or Command-Shift-J on a Mac. |
Microsoft Internet Explorer | Select Tools→Internet Options→Advanced, then uncheck the “Disable script debugging” box and check the “Display a notification about every script error” box. |
Mozilla Firefox | Select Tools→Error Console, or use the shortcut Ctrl-Shift-J on a PC or Command-Shift-J on a Mac. |
Opera | Select Tools→Advanced→Error Console. |
OS X users: although I have shown a way for you to use an Error Console with JavaScript in Safari, you may prefer to use Google Chrome (for Intel OS X 10.5 or higher), which in my view offers much more functionality for developers.
To try out whichever Error Console you are using, create a script with a small error. Example 13-3 is much the same as Example 13-1, but the final double quotation mark has been left off the end of the string “Hello World”—a common syntax error.
<html>
<head><title>Hello World</title></head>
<body>
<script type="text/javascript">
document.write("Hello World)
</script>
</body>
</html>
Type in this example and save it as test.html, then call it up in your browser. It should succeed in displaying only the title, not anything in the main browser window. Now call up the Error Console in your browser, and you should see a message such as the following (if using Firefox):
unterminated string literal document.write("Hello World) ---------------^
Note the handy arrow pointing to the start of the incorrect part of code. You will also be told that the offending code is at line 5.
In Microsoft Internet Explorer, the error message will look like this:
unterminated string constant
There’s no helpful arrow, but you are told that the problem is in line 5 at position 32.
Google Chrome will give this message:
Uncaught SyntaxError: Unexpected token ILLEGAL
You’ll be told that the error is in line 5, but not the exact location.
Opera will supply this message:
Syntax error while loading line 2 of inline script expected statement document.write("Hello World) -------------------------------^
Note that Opera differs from the other browsers by reporting the error to be on line 2 of the inline script, rather than referring to the line number of the entire HTML file. Also, Opera tries to point to the start of the problem, but gets only close to the first double quote.
Two browsers do quite well at pinpointing the error, though: Firefox highlights the opening double quote, which gives a big clue, and Internet Explorer says the error is at position 32, which is exactly where the closing double quote should be placed (although, because there’s no arrow pointing to this position, it’s necessary to count along to find it).
So, as you can see, on the whole Firefox probably provides the easiest to read and most accurate messages, and for that reason I would recommend it as the best browser for debugging JavaScript.
However, as you will learn, there are some major compatibility issues with Microsoft Internet Explorer, still the browser of choice for a significant portion of web surfers. So, as a developer, you’ll need to test your programs with various versions of this browser before you release them on a production server.
The Firebug plug-in for Firefox (http://getfirebug.com) is very popular among JavaScript developers, and is also worth a look.
If you will be typing in the following code snippets to try them
out, don’t forget to surround them with <script>
and </script>
tags.