External JavaScript file
An external JavaScript file can be created and embedded in multiple HTML
pages.
It enhances code reusability since a
single JavaScript file can be used across multiple HTML pages.
An external JavaScript file must be saved with a .js extension. It's
recommended to combine all JavaScript files into a single file to improve
webpage loading speed.
Example
"Create an external JavaScript file
that displays 'Hello world' in an alert dialog box."
Message.js
function msg(){
alert("Hello world");
}
"Include the JavaScript file in the
HTML page, and call the
JavaScript function when the button is
clicked."
Index.html
<html>
<head>
<title>JavaScript Alert</title>
</head>
<body>
<button
id="myButton">Click me!</button>
<script
src="script.js"></script>
</body>
</html>
Advantages of External Javascript
The following benefits come from creating an external JavaScript
file:
1. It allows code to be reused across multiple HTML files.
2. It improves code readability.
3. It is time-efficient because web browsers cache
external JS files, which reduces page loading time.
4. It allows web designers and developers to work on HTML and
JavaScript files simultaneously and independently,
avoiding code conflicts.
5. The code length is reduced because you only need to specify
the location of the JavaScript file.
Disadvantages of External Javascript
The following are the disadvantages of using external files:
1. A malicious user might download the coder's code using the
URL of the JavaScript file.
2. If two JavaScript files depend on each other, a failure in
one file can affect the execution of the other.
3. The web browser must make an additional HTTP request
to retrieve the JavaScript code.
4. Even a small change in the JavaScript code can lead to
unexpected results in all dependent files.
5. We need to review each file that depends on the shared
external JavaScript file.
6. If the code is only a few lines long, it's better to
implement it directly in the HTML file.