Adding JavaScript to an HTML Document

Here’s how to add JavaScript to an HTML5 document. Not all Web pages and have JavaScript, but a lot do these days.

But First …

Step by Step

Open your .html file with your editor.

<!doctype html>
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <h1>My Web Page</h1>
    <p>Well hello there.</p>
  </body>
</html>

To add JavaScript we have to use the <script></script> element. There are two ways to do this:

  1. Write the JavaScript directly into the HTML document between the <script> and </script> tags.
  2. Use <script src="main.js"></script> to load the JavaScript at that point in the HTML document.

Adding JavaScript to an HTML Document by Embedding It

You can embed <script></script> element anywhere in the HTML document <head></head> or <body></body> but we usually put them near the end of the body. Scripts will run at the point they are included so this prevents our page from lagging when it is loaded.

💬 These days there are things you can add to script to change this behavior, but we’ll keep things simple for now.

So let’s put our <script></script> at the bottom. And just put console.log('hello') inside to test it.

<!doctype html>
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <h1>My Web Page</h1>
    <p>Well hello there.</p>
    <script>console.log('hello')</script>
  </body>
</html>

Now let’s test it.

Adding JavaScript to an HTML Document by Sourcing It

First create the file.

touch main.js

It can just be a simple text file. You don’t have to do anything else to it (like change the permissions mode).

Now open that main.js file up and add something simple for now.

console.log('hello there')

Now we need to source the file from our index.html page in the opening <script> tag and remove the code between the <script></script> tags.

<script src='main.js'></script>

⚠️ Don’t forget the closing </script> tag. I know it is annoying that we need it even though there is nothing between the tags but that’s the way it goes. HTML is very old and has a lot of inherited quirks in it.