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 use the same JavaScript in multiple content pages?
To use the same JavaScript in multiple content pages, add the JavaScript code in an external JavaScript file. This approach promotes code reusability and easier maintenance across your website.
Creating an External JavaScript File
First, create an external JavaScript file. Let's say the following demo.js is our external JavaScript file:
function display() {
alert("Hello World!");
}
function calculate(a, b) {
return a + b;
}
function showMessage(message) {
alert("Message: " + message);
}
Including External JavaScript in HTML Pages
Now add the external JavaScript file to your HTML web pages using the <script> tag with the src attribute. In the same way, you can add it to multiple content pages.
<html>
<head>
<title>Page 1</title>
</head>
<body>
<form>
<input type="button" value="Show Alert" onclick="display()"/>
<input type="button" value="Calculate" onclick="alert(calculate(5, 3))"/>
<input type="button" value="Custom Message" onclick="showMessage('Hello from Page 1!')"/>
</form>
<script src="demo.js"></script>
</body>
</html>
Using the Same File in Another Page
You can include the same JavaScript file in any number of pages:
<html>
<head>
<title>Page 2</title>
</head>
<body>
<h1>Another Page</h1>
<button onclick="display()">Click Me</button>
<button onclick="showMessage('Welcome to Page 2!')">Welcome</button>
<!-- Same external JavaScript file -->
<script src="demo.js"></script>
</body>
</html>
Best Practices
File Placement: Place the <script> tag just before the closing </body> tag to ensure the HTML elements load before the JavaScript executes.
File Organization: Keep all JavaScript files in a dedicated folder like /js/ and reference them as src="/js/demo.js".
Multiple Files: You can include multiple external JavaScript files:
<script src="/js/utilities.js"></script> <script src="/js/main.js"></script> <script src="/js/demo.js"></script>
Advantages
| Advantage | Description |
|---|---|
| Reusability | Same code can be used across multiple pages |
| Maintainability | Update once, changes reflect everywhere |
| Performance | Browser caches the file, faster loading |
| Organization | Separates HTML structure from JavaScript logic |
Conclusion
External JavaScript files enable code reuse across multiple pages and improve maintainability. Use the <script src="filename.js"> tag to include the same JavaScript functionality on any page.
