CIS 119 - Adding JavaScript to a web page

Objectives

Adding JavaScript to a web page

JavaScript can be added to a web page in a number of ways:

Rules to remember

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>