External JavaScript Files

JavaScript allows us to create external JavaScript files that can be embedded in multiple HTML pages. This approach provides code reusability and simplifies the process of maintaining and updating JavaScript code.

JavaScript Example 1: Creating and Using an External JavaScript File

We can create an external JavaScript file (with a .js extension) and link it to multiple HTML pages. The external file is used for reusability, and it helps reduce redundancy.

Step 1: Create the External JavaScript File (message.js)

Example


function msg(){  
   alert("Hello Javatpoint");  
}

Step 2: Create the HTML File (index.html)

Example


<!DOCTYPE html>
<html>  
<head>
<script type="text/javascript">
function msg() {
    alert("Hello Shorat");
}
</script>  
</head>  
<body>  
<p>Welcome to JavaScript</p>  
<form>  
<input type="button" value="Click" onclick="msg()"/>  
</form>  
</body>  
</html>           
                         

Output

Welcome to JavaScript

Advantages of External JavaScript

Disadvantages of External JavaScript

Additional Information:

- External JavaScript files are typically used when there is a need for the same JavaScript code to be applied across multiple HTML pages.
- The src attribute of the <script> tag is used to link to the external JavaScript file.
- It is recommended to keep all JavaScript code in one external file to optimize the loading time, rather than spreading it across multiple files.
- If the JavaScript file is not cached, browsers will need to download the file again for each page load, which could reduce performance.