Chapter 5. Scripts and HTML Documents

IN THIS CHAPTER

  • Where to place scripts in HTML documents

  • What a JavaScript statement is

  • What makes a script run

  • Viewing script errors

In this chapter's tutorial, you begin to see how scripts are embedded within HTML documents and what comprises a script statement. You also see how script statements can run when the document loads or in response to user action. Finally, you find out where script error information may be hiding.

Where Scripts Go in Documents

Chapter 4 did not thoroughly cover what scripts look like or how you add them to an HTML document. That's where this lesson picks up the story.

The <script> tag

To assist the browser in recognizing lines of code in an HTML document as belonging to a script, you surround lines of script code with a <script>...</script> tag set. This is common usage in HTML, where start and end tags encapsulate content controlled by that tag, whether the tag set is for a form or a paragraph.

Depending on the browser, the <script> tag has a variety of attributes you can set that govern the script. One attribute, type, advises the browser to treat the code within the tag as JavaScript. Some other browsers accept additional languages (such as Microsoft's VBScript in Windows versions of Internet Explorer). The following setting is one that all modern scriptable browsers accept:

<script type="text/javascript">

Be sure to include the ending tag for the script. Lines of JavaScript code go between the two tags:

<script type="text/javascript"> ...

Get JavaScript® Bible, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.