How to Link JavaScript in HTML: Simple Guide
To link JavaScript in HTML, use the
<script> tag with the src attribute pointing to your JavaScript file. Place this tag inside the <head> or just before the closing </body> tag to load the script.Syntax
The basic syntax to link an external JavaScript file in HTML uses the <script> tag with the src attribute. The src attribute holds the path or URL to the JavaScript file.
- <script>: HTML tag to include JavaScript.
- src: Attribute specifying the file location.
- Closing </script> tag: Required to end the script element.
html
<script src="path/to/your-script.js"></script>Example
This example shows how to link a JavaScript file named script.js in an HTML page. The script runs when the page loads and shows a message in the browser console.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Link JavaScript Example</title> <script src="script.js"></script> </head> <body> <h1>Hello, JavaScript!</h1> </body> </html>
Output
Page shows a heading 'Hello, JavaScript!' and the browser console logs 'JavaScript is linked and running!'
Common Pitfalls
Common mistakes when linking JavaScript include:
- Forgetting the
srcattribute or misspelling it. - Placing the
<script>tag incorrectly, causing scripts to run before the page loads. - Not closing the
<script>tag properly. - Using relative paths incorrectly, leading to 404 errors.
Always check the file path and place scripts at the end of the <body> or use defer attribute for better loading.
html
<!-- Wrong way: missing src attribute -->
<script></script>
<!-- Right way: correct src and defer attribute -->
<script src="script.js" defer></script>Quick Reference
| Attribute | Description | Example |
|---|---|---|
| src | Specifies the path to the JavaScript file | |
| defer | Delays script execution until HTML parsing is done | |
| async | Loads script asynchronously without blocking HTML parsing |
Key Takeaways
Use the