Adding JavaScript to an HTML Document.
Tags: html, beginners, javascript, career
Published: 2020-11-15 12:26:55

---
series: JavaScript For Total Novice or Beginners.
title: Adding JavaScript to an HTML Document.
published: true
description: Adding Javascript to HTML document. In the head or body.
tags: html, beginner, JavaScript, career
//cover_image: https://direct_url_to_image.jpg
---

Welcome to this lesson, in this lesson, I will show you how to start using JavaScript on your websites.

Let's get started.

You can add JavaScript code to the HTML dedicated tag called 

```js
<script></script>
```

The script tag can be placed in the head section of your HTML, in the body section, or after the body close tag, depending on when you want the JavaScript to load.

The script tag is mostly included in the head section to separate it from the main content of the website.


Sometimes, you will need to create some HTML code and put it in the body of the page or perform some processes within the body section of the webpage with JavaScript. That may cause an error if the script tag and JavaScript code are added to the head section of the page because JavaScript code will have been executed before the body section is created. 

In short, JavaScript code can be included anywhere in an HTML document. 

### 1. Let's start by adding JavaScript to the head section. 

We add a script tag to this code and put alert("Ticking Clock") as its text node.
           
```js
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title> Ticking clock </title>
            <link rel="stylesheet" href="style.css"> 
            <script> 
              alert('Ticking clock'); 
            </script>
        </head>

        <body>
            <h1> Ticking clock </h1>
            <section id="container"></section>
        </body>
    </html>
```

Hey, Our focus here is on how to add JavaScript to a webpage so I am not going to explain the code in the script tag. 

Now, let's run it in the browser by launching it. It will be opened in the default browser on your computer.

Can you see that?

We have added the script tag to the head of our webpage.

### Adding JavaScript to the body section. 

Let's add the script tag that contains JavaScript code to the body section of this code:

Since we are not explaining the code here, let's just paste an already backed code here.

Bara bin bara boom boom boon!

Yeah! We have pasted the code.

```js
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title> My Images </title>
            <link rel="stylesheet" href="style.css">        
        </head>

        <body>
            <h1> My Images</h1>
            <section id="container"></section>

            <script type="text/javascript"> 
            function addImages(total) {
                let childElements = '';
                for(let count = 0; count < total; count++) {    
                    childElements += '<div><img src="https://dev-to-uploads.s3.amazonaws.com/i/gk8f3xlagjbvv9qqo1y1.jpg"></div>';             
                }
                return childElements;
            }
            let element = addImages(100);
            let container = document.getElementById('container');
            container.innerHTML = element;
        </script> 
        </body>
    </html>
```

Then, let's save the code to run it.

Boom! 

Do you see that? 

We have added "you" to the page. Oh! Not you, that's me. Oh! Sorry, that is an array of people. If you want to be there, you can add your personal image to it.

So, we have added script tag and JavaScript code to the body of our page.

Stop there! 

What is going to happen if I add the script tag and the JavaScript code in the head section of the page?

Just do it! Okay.

Let's do this. 

Copy and paste the script tag and the JavaScript code in it to the head section of the page.

Boom! It doesn't work.

Check the console. You will see that the container is null (not available).

It won't work because the body where the JavaScript code will add some things has not been created by the time the JavaScript code is executed in the head section. 

That happened because the browser rendered the page from top to bottom.

It will first render everything in the head before rendering the body.

Can you harvest your corn before it germinates? No, you can't?

In short, we have added the script tag to the body tag of our webpage.

It is also possible to add the script tag that contains JavaScript code to both the head and the body tags of our website. 

Let's do that by adding a script tag to the head section of this webpage.

Now, let's save it.

```js
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> My Images </title>
        <link rel="stylesheet" href="style.css">
        <script type="text/javascript">
            alert("JavaScript is added to the head section of this page");
        </script>
    </head>
   
   <body>
      <h1> My Images</h1>
        <section id="container"></section>

        <script type="text/javascript"> 
            function addImages(total) {
                let childElements = '';
                for(let count = 0; count < total; count++) {    
                    childElements += '<div><img src="https://dev-to-uploads.s3.amazonaws.com/i/gk8f3xlagjbvv9qqo1y1.jpg"></div>';             
                }
                return childElements;
            }
            let element = addImages(100);
            let container = document.getElementById('container');
            container.innerHTML = element;
        </script>   
   </body>
</html>
```

Boom! 

Do you see that? 

Both of the scripts are working on the page.

In short, we have added the script tag to both the head and body section of the webpage.

One more thing!

It easy to add JavaScript code within an HTML file, but that is only effective for scripts that are small or that run only on one page. 

I hope you know that?

It is not efficient and not advisable to put JavaScript code for larger scripts or scripts that will be used on many pages in HTML code because it can be very difficult to organize and maintain huge code with unrelated purposes in a file.

That takes us to adding JavaScript to HTML from a separate file.

We have a codebase called: codebox (a folder). 

The folder has two folders (css and js) and a file (index.html) in it. 

The CSS folder has style.css file and js folder has both code.js and base.js in it. Below is the structure of the folder.

### -codebox (folder)
  #### ------index.html
  #### ------css (folder
       ##### --- style.css
  #### ------js
       ##### --- code.js
       ##### --- base.js

We need to first put some code in the JavaScript files before we can use them on our page. So the contents of the above files are:

js/bade.js:
```js
     alert("JavaScript is added to the head section of this page");
```

js/code.js:
```js
    function tick() {
            let element = `
                <div>
                <h1>Hello, world!</h1>
                <h2>It is ${new Date().toLocaleTimeString()}.</h2>
                </div>
            `;
        let container = document.getElementById('container');
        container.innerHTML = element;
        }
    setInterval(tick, 1000);
```

Let's add JavaScript from separate files by adding 

```js
<script src="js/base.js"></script>
```
to the head section and  

```js
<script src="js/code.js"> </script>
```
 to the body of the page as in below:


```js
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Ticking clock </title>
        <link rel="stylesheet" href="css/style.css">

        <script src="js/base.js"></script>
    </head>
   
   <body>
      <h1> Ticking clock</h1>
        <section id="container"></section>

        <script src="js/code.js"> </script>   
   </body>
</html>
```
When you run the code in your browser, you should see an alert; then press ok. After that, you should see a time string in your local time in your browser.

hooooorayyyyyyyyyyyyyy!

As you can see, we have added JavaScript to an HTML file from two separate JavaScript files.

See you in the next lesson:

# One more thing

Are you having difficulties to learn and understand JavaScript and build projects with it? ***JavaScript for a Total Novice*** teaches JavaScript and Project Making Fundamentals with simple illustrations and examples that make everything so easy. You can now handle any difficult projects without fear.

Don't trust me, get a free previous to judge by yourself: https://bit.ly/3o3TMyg