To link a JavaScript file in HTML, use the <script>
tag with the src
attribute, specifying the path to your external .js
file. This is the standard and widely supported method for integrating JavaScript into modern websites.
Basic Syntax
<script src="your-script.js"></script>
- src: Path to your JavaScript file. It can be a relative path (e.g.,
js/script.js
) or an absolute URL (e.g.,https://example.com/scripts/app.js
).
Note: Ensure your JavaScript file ends with the
.js
extension, and the file itself should NOT contain<script>
tags.
Where to Place the <script> Tag?
At the end of <body>
(recommended)
This ensures the HTML content loads first, improving page performance.
<body>
<!-- Page content -->
<script src="your-script.js"></script>
</body>
In the <head>
with the defer
attribute
If you add defer
, the script loads AFTER the HTML is parsed, also improving performance.
<head>
<script src="your-script.js" defer></script>
</head>
Complete Example
Suppose you have the following files:
- index.html
- js/script.js
Filename: index.html
<!DOCTYPE html> <html> <head> <title>Link JavaScript File Example</title> </head> <body> <h1>Hello!</h1> <button onclick="showMessage()">Click Me</button> <script src="js/script.js"></script> </body> </html>
Filename: js/script.js
function showMessage() {
alert('Button was clicked!');
}
When the user clicks the button, the function from your JavaScript file will execute.
Notes and Best Practices
- Use the full or relative path to your JavaScript file in the
src
attribute. - If using multiple scripts, load libraries (like jQuery) before your custom scripts, and order matters.
- The
type="text/javascript"
attribute is optional, as modern browsers default to JavaScript. - For modern development, prefer placing JavaScript at the end of
<body>
or usedefer
for best performance.
This approach links your external JavaScript to your HTML, allowing you to reuse functions and logic efficiently across your website.