Including JavaScript Codes as External Files

This section provides a quick description of how to save JavaScript codes into separate files and include them into HTML documents with 'script' tags. A tutorial example is provided on calling a function stored in a separate JavaScript file.

Sometime, if you have a large amount of JavaScript code that needs to be shared by multiple HTML documents, you can store the JavaScript code in a separate file, and use the "script" tag to retrieve this tile.

The syntax of the "script" tag to retrieve a separate JavaScript code looks like this:

<script type="text/javascript" src="JavaScript_file_URL">

To test this feature, I wrote this JavaScript code and saved as a file, Hello_World_Function.js:

function printHello() {
   document.write('Hello World!');

Now I can modify my HTML document in the previous section to retrieve this file with a "script" tag:

<!-- Hello_World_Include.html
   Copyright (c) 2013 by Dr. Herong Yang,
<title>printHello() Function in an Include File</title>
<script type="text/javascript" src="Hello_World_Function.js">
<script type="text/javascript">

Of course, the output of the modified JavaScript page will be the same text: "Hello World!".

While testing this "src" attribute of the "script" tag, I also notice that the shorthand form of the empty tag does not work:

<script type="text/javascript" src="JavaScript_file_URL"/>

You must use the close tag </script> explicitly!

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

Web Browser Supporting JavaScript

 JavaScript Support in Web Browsers

 Including JavaScript Codes with HTML "script" Tags

 Including 'script' Tags in String Literials

 Escaping 'script' Tags in String Literials

 Using HTML Entities to Protect HTML Tags

Including JavaScript Codes as External Files

 DOM API - The "document" Object

 DOM API - The "window" Object

 DOM API - The "" Method

 Event Listeners and Objects

 'javascript:' Pseudo-URL Addresses

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications


 PDF Printing Version