Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write JavaScript in an External File?
JavaScript code can be written in external files with a .js extension and included in HTML documents using the <script> tag's src attribute. This approach improves code organization and reusability.
Why Use External JavaScript Files?
External JavaScript files offer several advantages:
- Code Reusability: Same file can be used across multiple HTML pages
- Better Organization: Keeps HTML and JavaScript code separated
- Caching: Browsers cache external files, improving page load times
- Maintainability: Easier to update and debug code
Creating an External JavaScript File
First, create a JavaScript file with the .js extension. For example, script.js:
function greetUser() {
alert("Welcome to our website!");
}
function showMessage() {
console.log("External JavaScript file loaded successfully!");
}
Including External JavaScript in HTML
Use the <script> tag with the src attribute to include the external file:
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
</head>
<body>
<h1>External JavaScript Demo</h1>
<button onclick="greetUser()">Greet User</button>
<button onclick="showMessage()">Show Message</button>
<script src="script.js"></script>
</body>
</html>
Multiple External Files
You can include multiple external JavaScript files by adding multiple <script> tags:
<!DOCTYPE html>
<html>
<head>
<title>Multiple External Files</title>
</head>
<body>
<h1>Multiple JavaScript Files</h1>
<!-- Include multiple external JavaScript files -->
<script src="utilities.js"></script>
<script src="main.js"></script>
<script src="events.js"></script>
</body>
</html>
Best Practices
-
File Placement: Place
<script>tags before the closing</body>tag for better page loading - File Organization: Group related functions in the same file
-
Naming Convention: Use descriptive filenames like
validation.js,animation.js - Path Specification: Use relative paths for local files, absolute URLs for external libraries
Example with File Structure
Consider this project structure:
project/
??? index.html
??? js/
??? main.js
??? utils.js
In index.html, reference the files using relative paths:
<!DOCTYPE html>
<html>
<head>
<title>Project Structure Example</title>
</head>
<body>
<h1>My Web Application</h1>
<script src="js/utils.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Conclusion
External JavaScript files improve code organization, reusability, and performance. Use the src attribute in <script> tags to include them in your HTML documents.
