To add JavaScript to a web page, you can include it directly in the HTML file using a script
element. Here's an example of how to do this:
<!DOCTYPE html> <html> <head> <title>My Web Page</title> </head> <body> <h1>Welcome to My Web Page</h1> <p>Here is some content on my web page.</p> <script> console.log("Hello, World!"); </script> </body> </html>
The script
element should be placed in the body
of the HTML document, and the JavaScript code should be placed between the opening <script>
and closing </script>
tags.
Alternatively, you can also include a JavaScript file in your HTML file using the src
attribute of the script
element:
<!DOCTYPE html> <html> <head> <title>My Web Page</title> </head> <body> <h1>Welcome to My Web Page</h1> <p>Here is some content on my web page.</p> <script src="myscript.js"></script> </body> </html>
In this case, the script
element should still be placed in the body
of the HTML document, but the src
attribute should be set to the URL of the JavaScript file that you want to include.
You can also include JavaScript in the head
of an HTML document, but it is generally a good practice to include it at the bottom of the body
element to ensure that the content of the page is loaded before the JavaScript is executed. This can help improve the performance of your web page.