The Java Connection
- » Java, created by » Sun Microsystems, is a full computer programming language like C++, suitable for writing complete, large-scale programs.
A scripting language can be thought of as a lightweight programming language; one that can be interpreted by a browser without needing to be compiled first. The script is actually just some commands that the browser has to do.
The two share many similarities. Most prominent of these is that they are both forms of Object-Oriented Programming, or OOP. This means that you work with small objects that are combined together to form larger objects. We'll get into that more in a minute.
.js), or write blocks of code right into your HTML documents with the
<script> tag. The usual choosing criteria apply — if you're using the same script on many pages, link to an external file; otherwise embed.
We'll do our first example with an embedded script. This will simply print a line of text to the page.
When you place that in your code the text Hello World will appear on your screen wherever you put it. Like so:
script tag encloses any script code you want to use. The
type attribute we have in there alert the browser to the type of script it is about to deal with (there are others, like VBScript), and so helps it to interpret the code.
The comments around the script code are there so that old browsers that don't understand the
To import scripts from external JS files, save the code in a text file with the
.js extension; without the
script tags and comments. In this case the code would just be the
document.write("Hello World!"); part (although this won't do much on its own). We then link to this document, in the page's
Now all of the methods and variables that are in that file are available to use in the page. We'll learn more about that in the next tutorial.
We should always place includes in the
head so that the browser is ready to execute scripts when the user calls for them. If a user clicked a button that called for a script that the browser wasn't aware of yet, you'd get an error. Having them in the
head means they're always ready before they're needed.
A Simple Script
So what did our code above actually accomplish? Take another look at it.
We start by taking control of the
document object, and use its
We'll do one more example before wrapping up for this tutorial. This script will create some HTML and text.
Note that when quoting attribute values, you have to use single quotes, as if you used double quotes the
write method would think the string was over prematurely, and you'd get an error.
<noscript> content will be redundant. However, you should always try and use this tag when appropriate — it helps keep your content accessible.
Read our review.