Scripts may also be stored in external files.
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. |
Placing scripts in external files offers several advantages:
To include multiple script files on a single page, use multiple script tags:
Example
<script src=”myScript1.js”></script> |
An external script can be referenced in three different ways:
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> |