External JavaScript

Scripts can also be placed in external files. External scripts are practical when the same code is used in many different web pages. JavaScript files have the file extension .js. You can place an external script reference in <head> or <body> as you like. The script will behave as if it was located exactly where the <script> tag is located. To use an external script, put the name of the script file in the src (source) attribute of the <script> tag:

The files: Displayed by browser:

THE myScript.js FILE:

function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}

THE HTML FILE:

<body>
<h1>External JavaScript</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p>
<script src="myScript.js"></script>
</body>

External JavaScript

A Paragraph

Note: myFunction is stored in an external file called "myScript.js".

Placing JavaScripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads
Good habit External scripts cannot contain <script> tags.
BackTable of ContentsNext