Chapter 7. 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

Chapter 4, "JavaScript Essentials," covered many of the basics of how to combine JavaScript with HTML documents. This chapter's tutorial reviews how scripts are linked to 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.

Connecting Scripts to Documents

We use the script element to tell the browser to treat a segment of text as script and not as HTML. Whether our script is an external file linked to the HTML document or embedded directly in the page itself, the <script>...</script> tag set encapsulates the script.

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" ...>...<script>

Be sure to include the ending tag for the script. Your JavaScript program code goes either into an external file specified in the src attribute:

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

or between the ...

Get JavaScript® Bible, Seventh 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.