JavaScript can be written in various places within an HTML document or in external files. Here are the common places to include JavaScript in your web pages:
1. Inline JavaScript (Within HTML Tags)
You can write JavaScript directly within HTML tags using event attributes like onclick, onmouseover, etc.
Example:
<button onclick="alert('Hello!')">Click Me</button>
- The JavaScript is written directly inside the
onclickattribute of the<button>element.
2. Internal JavaScript (Inside the <script> Tag in HTML)
You can place JavaScript inside a <script> tag in the <head> or <body> section of your HTML document.
Example (in the <head> section):
<!DOCTYPE html>
<html>
<head>
<script>
function showAlert() {
alert('Hello from the head!');
}
</script>
</head>
<body>
<button onclick="showAlert()">Click Me</button>
</body>
</html>
Example (in the <body> section):
<!DOCTYPE html>
<html>
<body>
<h2>Internal JavaScript in the Body</h2>
<script>
document.write("This is written using JavaScript in the body section.");
</script>
</body>
</html>
3. External JavaScript (Using an External .js File)
You can write JavaScript in a separate .js file and link it to your HTML using the <script> tag with the src attribute.
HTML Example:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h2>External JavaScript File</h2>
<button onclick="externalAlert()">Click Me</button>
</body>
</html>
JavaScript (in script.js):
function externalAlert() {
alert('Hello from external JavaScript!');
}
- The JavaScript is kept in a separate file (
script.js), which is linked to the HTML document using the<script src="script.js"></script>tag.
Where to Place JavaScript?
- In the
<head>section: JavaScript in the head runs before the page is fully loaded, so it’s better for functions or operations that don’t depend on the HTML body being rendered. - At the bottom of the
<body>section: This is recommended when you want the HTML content to load first and JavaScript to run afterward, improving page performance.
Summary:
- Inline JavaScript: For small, event-driven scripts within HTML elements.
- Internal JavaScript: For scripts embedded in the HTML file using the
<script>tag. - External JavaScript: Best for separating JavaScript from HTML, allowing reusability and easier management.
