1.6 Where to Put JavaScript>Before learning JavaScript, you should be familiar with HTML and how to create an HTML document. This doesn't mean that you have to be an expert, but you should be familiar with the structure of HTML documents and how the tags are used to display various kinds of content on your browser. Once you have a static HTML document, then adding basic JavaScript statements is quite easy. (See Appendix B for an HTML tutorial.) Client-side JavaScript programs are embedded in an HTML document between HTML head tags <head> and </head> or between the body tags <body> and </body> . Many developers prefer to put JavaScript code within the <head> tags, and at times, as you will see later, it is the best place to store function definitions and objects. If you want text displayed at a specific spot in the document, you may want to place the JavaScript code within the <body> tags (as shown in Example 1.2). Or you may have multiple scripts within a page, and place the JavaScript code within both the <head> and <body> tags. In either case, a JavaScript program starts with a <script> tag, and and ends with a </script> tag. And if the JavaScript code is going to be long and involved, or may be reused, it can be placed in an external file (ending in .js ) and loaded into the page. When a document is sent to the browser, it reads each line of HTML code from top to bottom, and processes and displays it. As JavaScript code is encountered , it is read and executed by the JavaScript interpreter until it is finished, and then the parsing and rendering of the HTML continues until the end of the document is reached. Example 1.21 <html> 2 <head><title>First JavaScript Sample</title></head> 3 <body bgcolor="yellow" text="blue"> 4 <script language = "JavaScript" type="text/javascript"> 4 document.writeln("<h2>Welcome to the JavaScript World!</h1>"); 5 </script> 6 <font size="+2">This is just plain old HTML stuff.</font> 7 </body> 8 </html> EXPLANATION
|