Inserting JavaScript into a Web Page

Information - Put Your Scripts in <head>

JS scripts are usually put in the <head> of a document so that they are loaded first. Scripts are enclosed in the <script>, </script> tags. The segment of an HTML page below puts shows the format for inserting JS.

<html>
<head>
<title>Inserting JavaScripts</title>
<script language="JavaScript">
//The script itself goes here
</script>

</head>
<body>
</body>
</html>

Information - Hiding Scripts From Old Browsers

Older browsers don't execute JS. Instead, they display the text of the JS on the screen along with your page text. This can be disconcerting to some users. To prevent this from happening, use the JS comment tags to "hide" the JS from old browsers. The comment tags are <!-- and // -->.

<html>
<head>
<title>Inserting JavaScripts</title>
<script language="JavaScript">
<!--
//The script itself goes here
// -->
</script>

</head>
<body>
</body>
</html>

Information - Scripts Are Executed Before the User Interacts

JavaScripts that are in the <head> execute before the user sees the page. The script below calls the alert box which the user sees before he/she sees any text on the web page.

<html>
<head>
<title>A Script to Call the Alert Box</title>
<script language="JavaScript">
alert("This is the alert box")
</script>

</head>
<body>
<center><h3>This text appears after the alert box appears and is dismissed.</h3></center>
</body>
</html>


Exercise 1

The script above illustrates five things:

  • puts the script between the <head> tags
  • illustrates how to put comments inside JavaScripts
  • illustrates how comments can be used to hide JS from old browsers
  • illustrates how to create a popup alert box
  • illustrates how scripts in the head execute before anything on the web page

1. Open Notepad and type in the script immediately above Exercise 1 exactly as it is shown.
2. Save the file on the Desktop. Give it a filename that ends in HTM or HTML, not TXT.
3. Double click the saved file to open it in the browser to test.
4. If your script has no errors, it will look like this.
5. If there is a typo in your script, it will look something like this.