Linking a JavaScript file to an HTML document is a fundamental skill for web development. There are a couple of ways to do this, depending on whether you want to include the JavaScript directly in the HTML file or link to an external JavaScript file. Here’s a guide on both methods:
1. Internal JavaScript
You can include JavaScript directly within your HTML file using the <script>
tag. This method is useful for small scripts or when you’re quickly testing some code.
<html>
<head>
<title>Internal JavaScript Example</title>
</head>
<body>
<h1>Hello World</h1>
<script>
document.querySelector('h1').textContent = 'Hello JavaScript!';
</script>
</body>
</html>
2. External JavaScript
For larger scripts or when you want to keep your HTML and JavaScript separate, you can link to an external JavaScript file. This is the preferred method for most projects.
Step-by-Step:
-
Create a JavaScript File:
Create a file with a
.js
extension. For example,script.js
.javascript// script.js
document.querySelector('h1').textContent = 'Hello JavaScript!';
-
Link the JavaScript File in Your HTML:
Use the
<script>
tag with thesrc
attribute to link the external JavaScript file in your HTML document. Place the<script>
tag at the end of the<body>
section to ensure the HTML elements are loaded before the JavaScript runs.html
<html>
<head>
<title>External JavaScript Example</title>
</head>
<body>
<h1>Hello World</h1>
<script src="script.js"></script>
</body>
</html>
Important Considerations:
-
Script Placement: Placing the
<script>
tag at the end of the<body>
section ensures that the DOM is fully loaded before the script runs. If you place it in the<head>
, you may need to use thedefer
attribute to achieve the same effect.html<head>
<script src="script.js" defer></script>
</head>
-
Handling Asynchronous Scripts: Use the
async
attribute if you want the script to download asynchronously with the rest of the page, but note that it will execute as soon as it is downloaded, potentially before the DOM is fully constructed.html<head>
<script src="script.js" async></script>
</head>
Example
Here’s a complete example demonstrating how to link an external JavaScript file:
-
Create the HTML File (
index.html
):html
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph.</p>
<script src="script.js"></script>
</body>
</html>
-
Create the JavaScript File (
script.js
):javascriptdocument.querySelector('h1').textContent = 'Hello JavaScript!';