Including Scripts in Web Pages - HTML 4

Because a JavaScript script is a totally separate animal from HTML markup, you have to contain this JavaScript beast inside an HTML container tag, <script> and </script>. You can put a script in one of two places on an HTML page:

  • Within the <head> and </head> tags (this is called a header script)
  • Within the <body> and </body> tags (this is called a body script)

Header scripts contain code that you either want to be processed before the page loads or else want to have available to be called by other scripts in your Web page. Body scripts are executed when the <body> tag is processed. Typically, body scripts are used to generate HTML content for the page.

Listing shows an example of a header script. This simple script pops up a welcoming message box when the user loads the page.

Listing : Header Script

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>My JavaScript page</title>
<script language=”Javascript” type=”text/javascript”>
alert(“Welcome to my JavaScript page!”)
</script>
</head>
<body bgcolor=”#FFFFFF”>
<h2>This script pops up a message box for the user.</h2>
</body>
</html>

The preceding <script> tag has two attributes:

  • language=”Javascript” tells the browser which scripting language the document uses.
  • type=”text/javascript” tells the browser that the script is plain text in JavaScript.

The script itself, alert(“Welcome to my JavaScript page!”), is straightforward. The alert() method displays a message box that pops up on top of the browser window and shows a customized message to the Web page visitor. You specify the message you want displayed by enclosing the text within quotation marks and putting the text string inside the alert() method’s parentheses, as shown in Listing (Note: Curly quotes and single quotes won’t work.) Make sure you close the script with the </script> tag, and your script is ready to go.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

HTML 4 Topics