To include an external JavaScript file in a file, use the script tag.
<script src='../filename.js'></script>
The src attribute refers to the path where the included file resides. The file specified is a file that contains JavaScript only and has no script tags.
Note that the end script tag immediately follows the beginning script tag.
Why use the script tag to include a JavaScript file instead of embedding the JavaScript directly within the HTML file? A number of advantages are listed below:
1) Allows for the separation of presentation and scripting.
2) Files can be included in an HTML page from other web servers.
3) Provides for modular and reusable code. For instance, a function can be created once, placed in the .js file and then used among multiple pages.
4) Placing JavaScript in it’s own file causes the browser to cache the JavaScript when it is used among multiple pages.
Filed under: JavaScript