Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

External JavaScript

Scripts may also be stored in external files.

External file: myScript.js

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

External scripts are practical for reusing the same code across multiple web pages and typically have a .js file extension. To include an external script, reference the file name in the src attribute of a <script> tag.

Example

<script src=”myScript.js”></script>

You can place an external script reference in the <head> or <body>, and it will execute as if located where the <script> tag appears.

External scripts cannot include <script> tags within them.

External JavaScript Advantages

Placing scripts in external files offers several advantages:

  • Separates HTML and code
  • Makes both HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loading times

To include multiple script files on a single page, use multiple script tags:

Example

<script src=”myScript1.js”></script>
<script src=”myScript2.js”></script>

External References

An external script can be referenced in three different ways:

  • Using a full URL (a complete web address).
  • Using a file path (e.g., /js/).
  • Without any specified path.

For instance, in this example, a full URL is utilized to link to myScript.js:

Example

<script src=”https://www.code7school.com/js/myScript.js”></script>

In this instance, a file path is employed to link to myScript.js.

Example

<script src=”/js/myScript.js”></script>

This example doesn’t utilize any path to connect to myScript.js: reword it.

Example

<script src=”myScript.js”></script>