CIS 119 - Adding JavaScript to a web page
Objectives
- add JavaScript to a web page
- include an external JavaScript file in a web page
- add inline JavaScript
- write XHTML code that will allow JavaScript to pass validation
- add comments within JavaScript source
Adding JavaScript to a web page
JavaScript can be added to a web page in a number of ways:
- A block of JavaScript contained within a script element can be included in
the head element of a web page. This is a common technique, but does lead
to one potential problem. Since the head element is processed before the
body element, the code in the head element can not act on elements in the
body until after the body has been processed and displayed. It turns out
that there are easy ways to do this for almost any code you would want to write.
- A block of JavaScript contained within a script element can be included in
the body element of a web page. This is a common technique for code that will
be run a single time to dynamically generate web page content.
- JavaScript code can be placed in a separate file (usually with a .js extension)
and then included in the head element of a document using the script tag.
- JavaScript code can be included inline as values for certain attributes. Usually
the attributes are for handling events such as mouse clicks, but JavaScript can
also be used as the value of an href attribute.
Rules to remember
- Place code to be used later within functions that can be called when needed. The
functions can be called using event handlers at a later time.
- Code placed in the head element can not immediately be executed and operate on
elements within the web page since the web page body is not created until after
the head element is finished being processed.
- Good coding practice is to use external JavaScript files instead
of mixing JavaScript code with HTML markup.
Example of JavaScript written in a separate file.
// filename: welcome.js
alert("Welcome to JavaScript.");
Example of including a separate JavaScript file in a web page.
<html>
<head>
<title>Title of page</title>
<script type="text/javascript" src="welcome.js"></script>
</head>
<body>
This is where the displayable content goes.
</body>
</html>
Example of including JavaScript within a web page using the script element.
Note: The CDATA delimiters are present to make the web page validate as proper XHTML.
<html>
<head>
<title>Title of page</title>
<script type="text/javascript">
/* <![CDATA[ */
alert("Welcome to JavaScript.");
/* ]]> */
</script>
</head>
<body>
This is where the displayable content goes.
</body>
</html>
Example of including JavaScript as the value of an event handling attribute
of an XHTML tag.
<html>
<head>
<title>Title of page</title>
</head>
<body onload="alert('Welcome to JavaScript');">
This is where the displayable content goes.
</body>
</html>