How to Add JavaScript to an HTML Page: Simple Guide
You add JavaScript to an HTML page by using the
<script> tag. You can place JavaScript code directly inside this tag or link to an external JavaScript file using the src attribute.Syntax
The <script> tag is used to include JavaScript in an HTML page. It can contain code directly or link to an external file.
<script>...code...</script>: Inline JavaScript inside the HTML.<script src="file.js"></script>: Links to an external JavaScript file.
html
<script> // Inline JavaScript code alert('Hello from inline script!'); </script> <script src="script.js"></script> <!-- External file -->
Example
This example shows how to add JavaScript directly inside the HTML page to display a message when the page loads.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Example</title> </head> <body> <h1>Welcome!</h1> <script> // Show a greeting message alert('Hello! This is JavaScript running in your page.'); </script> </body> </html>
Output
A popup alert box with the message: Hello! This is JavaScript running in your page.
Common Pitfalls
Common mistakes when adding JavaScript to HTML include:
- Placing the
<script>tag in the<head>without waiting for the page to load, causing errors if scripts access elements not yet loaded. - Forgetting the
srcattribute when linking external files or using wrong file paths. - Not closing the
<script>tag properly.
To avoid errors, place scripts just before the closing </body> tag or use event listeners to run code after the page loads.
html
<!-- Wrong: script in head accessing body element too early -->
<head>
<script>
document.getElementById('demo').textContent = 'Hello'; // May fail if element not loaded
</script>
</head>
<body>
<p id="demo"></p>
</body>
<!-- Right: script at end of body -->
<body>
<p id="demo"></p>
<script>
document.getElementById('demo').textContent = 'Hello'; // Works because element is loaded
</script>
</body>Quick Reference
Summary tips for adding JavaScript to HTML:
- Use
<script>tags to add JavaScript. - Place scripts at the end of the
<body>for better loading. - Use
srcattribute to link external files. - Always close
<script>tags properly. - Use event listeners like
DOMContentLoadedto run code after page loads.
Key Takeaways
Add JavaScript to HTML using the