About Lesson
Let’s talk about where to place JavaScript in an HTML file. There’s a lot of flexibility here, but we’ll cover some preferred methods:
- Script in <head>…</head> Section: This is a popular choice. You can put your JavaScript right between the <head> tags in your HTML file.
- Script in <body>…</body> Section: Another common approach is to include your JavaScript within the <body> tags. This is handy if you want your script to run as the page loads.
- Script in Both <head> and <body> Sections: Sometimes, you might want to mix things up and include scripts in both the <head> and <body> sections. It’s totally doable!
- Script in an External File: If you find yourself reusing the same JavaScript code across multiple pages, you can create an external file with a “.js” extension and include it in your HTML file.
Here’s the basic syntax for adding JavaScript using the <script> tag:
<script>
// Your JavaScript code goes here
</script>
Now, let’s dive into some examples:
- JavaScript in <head>…</head> Section: This is great for scripts that need to run based on user events, like clicking a button.
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World");
}
</script>
</head>
<body><input type=“button” onclick=“sayHello()” value=“Say Hello” />
</body>
</html>
- JavaScript in <body>…</body> Section: Use this if you want your script to generate content as the page loads.
<html>
<head>
</head>
<body><script type=“text/javascript”>
document.write(“Hello World”);
</script>
<p>This is the webpage body</p>
</body>
</html>
- JavaScript in Both <head> and <body> Sections: Sometimes, you might want to mix things up and include scripts in both the <head> and <body> sections. It’s totally doable!
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World");
}
</script>
</head>
<body><script type=“text/javascript”>
document.write(“Hello World”);
</script>
<input type=“button” onclick=“sayHello()” value=“Say Hello” />
</body>
</html>
- JavaScript in External File: For reusable code, you can create an external JavaScript file and include it in your HTML.
<!-- filename.js -->
function sayHello() {
alert("Hello World");
}
<html>
<head>
<script type="text/javascript" src="filename.js"></script>
</head>
<body>
...
</body>
</html>
That’s it! With these methods, you’ll have full control over where and how you include JavaScript in your HTML files. Happy coding! 🎉