Share this Page URL

Chapter 17. The Programmable Page: Addin... > The Programmable Page: Adding JavaSc... - Pg. 193

The Programmable Page: Adding JavaScripts to Your Pages 193 Using the <SCRIPT> Tag JavaScript code goes right inside the Web page, just like HTML tags. When a JavaScript-savvy browser (such as Netscape 2.0 and later and Internet Explorer 3.0 and later) accesses the page, the JavaScript code is executed and the program does its thing. For example, the program might check the time of day and display an appropriate welcome message, or you could embed a calcu- lator right on the page. JavaScripts reside between the <SCRIPT> and </SCRIPT> tags and always take the following form: <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript"> <!-- The script commands go here. //--> </SCRIPT> Note the use of HTML comment tags. These ensure that JavaScript-feeble browsers don't try to read the JavaScript commands. Webmaster Wisdom In the same way that HTML has comment tags that tell the browser to ignore the text and tags between them, programmers can also add comments to scripts. To do so, they insert two slashes (//) at the beginning of each line they want ignored. A common example is the line just above the </SCRIPT> end tag: //--> You have to put the comment slashes at the beginning to prevent JavaScript from trying to "execute" the end tag of the HTML comment (-->). Inserting the Script Where you store the script in your page depends on what it does: · If the script writes text to the page, you position the script where you want the text to appear. · Otherwise, you position the script inside the page header (that is, between the <HEAD> and </ HEAD> tags). Using an External JavaScript File Besides having your scripts snuggle up to your regular page tags, it's also possible in some cases to plop the scripts into a separate file. Although this is really only for advanced users who know what they're doing, it's worthwhile because it has three benefits: · It makes it easier to reuse a script because you need to tell the browser only the name and location of the separate file. You don't have to insert the script itself into all your pages.