Including outside JavaScript code

When your code becomes large, you are likely to find that you are reusing identical JavaScript code on multiple pages of your web site. For example, if you have a dynamic menu common to all or most of your pages of your web site, it will make sense to reuse the JavaScript code that creates the dynamic menu. It is not efficient to maintain identical code in multiple files. The idea is to place your identical JavaScript code in one file (with a file extension .js) and use that file where ever needed. If you ever need to make any changes to your JavaScript code, you will be making changes just to your JavaScript file instead of everywhere else you use the code.

To create a .js file, simply place your JavaScript code in an empty file and save the file with .js file extension. Note when you place your JavaScript code in an external file, you do not use the <script> and </script> tags. You use the <script> and </script> tags when you want to use the external JavaScript file.

By adding the src attribute to the <script> tag, you can specify a relative or absolute URL for a JavaScript file, as in the following:

<script language="javascript" src="JavaScriptFileName.js">
</script>

The following shows an example of code inside an external JavaScript file called ExternalJavaScript.js:

// Author: Scripting Master
// Description: This JavaScript code is placed in a file called ExternalJavaScript.js
document.write ("A JavaScript print statement inside an external JavaScript file."); // prints a message

To link the code shown above in any of your web page, use

<script language="javascript" src="http://www.scriptingmaster.com/javascript/ExternalJavaScript.js">
/* The above line linked a JavaScript file called "ExternalJavaScript.js" via a src attribute of a <script> tag. */
</script>

Note above our src attribute is set to an absolute path (http://www.scriptingmaster.com/javascript/ExternalJavaScript.js) but you can use a relative path for your own scripts. With the above <script> tag, we are saying we want to execute the JavaScript statement(s) inside a file called ExternalJavaScript.js. The following shows the output when statements are executed: