JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
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"> </script>
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:
<html> <!-- Hello_World_Head_Include.html Copyright (c) 2002 HerongYang.com. All Rights Reserved. --> <head> <title>printHello() Function in an Include File</title> <script type="text/javascript" src="Hello_World_Function.js"> </script> </head> <body> <pre> <script type="text/javascript"> printHello(); </script> </pre> </body> </html>
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
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
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
type="text/javascript" or language="JavaScript"
JavaScript Version Supported by Browsers
Including 'script' Tags in String Literals
Escaping 'script' Tags in String Literals
Using HTML Entities to Protect HTML Tags
►Including JavaScript Codes as External Files
DOM API - The "document" Object
DOM API - The "window.open" Method
'javascript:' Pseudo-URL Addresses
JavaScript Console in Google Chrome
JavaScript Console in Mozilla Firefox
JavaScript Console in Apple Safari
JavaScript Console in IE (Internet Explorer)
Server-Side and Client-Side Web Scripting
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