Your First Script

You use the script tag to embed JavaScript in an HTML page. For example, Listing B.1 shows a simple script.

Listing B.1. A simple JavaScript script.
<html>
<head>
<title>Your First Script</title>
<body>
<script type="text/javascript">
    document.write("Hi there! I am JavaScript!")
</script>
</body>
</html>

In this case, the script consists of just one line of code:

document.write("Hi there! I am JavaScript!")

It uses one of the available objects, document, which will be discussed later and which is basically the page you see in your browser. Open this HTML page in any browser and you should see an empty page with “Hi there! I am JavaScript!” printed on it.

If you are a Java or C++ programmer, you will be tempted to put a semicolon in the end of the line of code. All right, do it! Semicolons are optional in JavaScript unless you have multiple statements in the same line of code. It is recommended to always use a semicolon at the end of your statement.

Have you ever looked at the source code of a web page with JavaScript embedded in it? If yes, then most probably you’ve seen some unusual comments, like the one here:

<script type="text/javascript">
<!--
  document.write("Hi there! I am JavaScript!")
//-->
</script>

This is for Web browsers that do not support JavaScript. These very old browsers do not understand what <script> means and would just print your JavaScript code on the page. With comments after <script>, older browsers will not display the script.

If your script is long, it is good practice to put your script in a separate file and then reference it from the HTML file by using the src attribute of the script tag. For example, the following script tag references an external file named try.js.

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

..................Content has been hidden....................

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