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.
  • It is good practice to include large JavaScript libraries as links at the end of the body element of the HTML page. That helps to not delay the loading and display of the web page.

Example of JavaScript written in a separate file.

Example of including a separate JavaScript file in a web page.

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.

Example of including JavaScript as the value of an event handling attribute of an XHTML tag.