To add JavaScript to an HTML file, you have a few options. Here are the common methods:
Inline JavaScript:You can add JavaScript code directly within the HTML file using the <script> tag inside the <head> or <body> section. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script>
// Inline JavaScript
function greet() {
alert('Hello, world!');
}
</script>
</head>
<body>
<button onclick="greet()">Click me</button>
</body>
</html>
External JavaScript File:
You can create a separate .js file and link it to your HTML using the <script> tag's src attribute:
-
Create a JavaScript File:
For example, create a file named
script.js
and write your JavaScript code there.// script.js function greet() { alert('Hello, world!'); }
- Link the JavaScript File: In your HTML file, include the <script> tag with the src attribute pointing to your JavaScript file.
- It's recommended to place <script> tags just before the closing </body> tag for better page loading performance.
- Keep your JavaScript code separate from HTML whenever possible for better maintainability.
-
Use event listeners or modern approaches (like
addEventListener
) rather than inline event handlers for better code organization and separation of concerns.
Remember, these are basic methods for including JavaScript in HTML. As your projects grow, consider using modern JavaScript practices, module systems, and bundlers for better code management and maintainability.