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
- Reusability: The external JavaScript file can be used in multiple HTML files, saving time and reducing redundancy.
- Code Readability: It allows easy readability as the JavaScript code is separated from the HTML structure.
- Efficiency: Web browsers cache external JavaScript files, which helps in reducing the page loading time.
- Parallel Work: Designers and developers can work on HTML and JavaScript files independently, without facing conflicts.
- Reduced Code Length: The length of the code in the HTML file is reduced as we only need to specify the path of the external JS file.
Disadvantages of External JavaScript
- Security Risk: Anyone can potentially access the JavaScript code through the URL of the external file.
- Dependency Issues: If two JavaScript files are dependent on each other, a failure in one file can affect the execution of others.
- Additional HTTP Request: The browser needs to make an extra HTTP request to fetch the external JS file, which could delay the loading time.
- Unexpected Results: A small change in the external JS file can affect all the HTML files that depend on it, potentially causing unexpected behavior.
- File Management: It is important to keep track of all the files that depend on the external JavaScript file to avoid conflicts or errors.
- Small Scripts: For small amounts of JavaScript code, it may be more efficient to include the code directly within the HTML document.
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.