External JavaScript File

External JavaScript files are a great way to increase efficiency and improve maintainability across a website.

You can place all your scripts into an external file (with a .js extension), then link to that file from within your HTML document. This is handy if you need to use the same scripts across multiple HTML pages, or a whole website.

To link to an external JavaScript file, you add a src attribute to the HTML <script> tag and specify the location of the external JavaScript file.

Linking to an external JavaScript file

Here's an example of linking to an external JavaScript file. The file called external_javascript.js contains all the JavaScript code. So, there's no need to place any other JavaScript between the tags.

<script src="external_javascript.js"></script>

Contents of your external JavaScript file

The code in your .js file should be no different to the code you would normally have placed in between the script tags.

But remember, you don't need to add the <script> tag again — it is already on the HTML page calling the external file!

Placement of the External JavaScript

External JavaScript files are commonly placed within the document's <head> tags. However, this is not a necessity. You can place the <script> element anywhere on the document.

For performance reasons, JavaScript is often placed at the bottom of the document, just before the closing <body> tag. This allows the rest of the page to load first, before making the call to the external file.

However, not all JavaScript can be placed at the bottom of the document. If another script on the page needs that particular piece of JavaScript at load time, you will need to place the external JavaScript before the script that needs it.