Slide 11.d: JavaScript where to …
Slide 11.f: JavaScript variables
Home

JavaScript Where to … (Cont.)


Scripts in both the Head and the Body Section
You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
 <html>
  <head>
   <script type="text/javascript">
    alert( "JavaScript is in the head." );
   </script>
  </head>
  <body>
   <script type="text/javascript">
    alert( "JavaScript is in the body." );
   </script>
  </body>
 </html>

Using an External JavaScript
Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. Note that the external script cannot contain the <script> tag! To use the external script, point to the .js file in the src attribute of the <script> tag. Remember to place the script exactly where you normally would write the script!

 <html>
  <body>
   <script src="e_2.js" />
  </body>
 </html>
 var  name =
   prompt( "Please enter your name:" );
 if (( name != null ) && ( name != "" )) {
  document.write( "Good morning, "+name );
 }
e_2.js

The method prompt of the object window displays a prompt dialog box with a message and an input field. The concatenation operator + concatenates two string values together, returning another string that is the union of the two operand strings.

Demonstration