To make your web pages interactive, you need to include JavaScript in your HTML files. This is done using the <script>
tag.
There are two main ways:
-
Inline JavaScript: You can write JavaScript code directly between the opening
<script>
and closing</script>
tags.<!DOCTYPE html> <html> <head> <title>My First JS Page</title> </head> <body> <h1>Welcome!</h1> <script> console.log("JavaScript is running from inline script!"); alert("Hello from the page!"); // alert creates a pop-up dialog </script> </body> </html>
-
External JavaScript File (Recommended): For better organization, especially with larger scripts, it's best to put your JavaScript code in a separate file (e.g.,
script.js
) and link it to your HTML.script.js:
// This is in script.js console.log("JavaScript is running from an external file!"); alert("Hello from external script!");
index.html:
<!DOCTYPE html> <html> <head> <title>My JS Page</title> </head> <body> <h1>Welcome!</h1> <script src="script.js"></script> <!-- Link to the external file --> </body> </html>
Where to place the <script>
tag?
It's common practice to place <script>
tags just before the closing </body>
tag. This ensures that the HTML content of the page is loaded and parsed before the script tries to interact with it, which can prevent errors and improve perceived page load speed.