How to Include Javascript Code in HTML Page



(adsbygoogle = window.adsbygoogle || []).push({});

(adsbygoogle = window.adsbygoogle || []).push({});

Hello, I hope you all are doing well. In the last post, I have shared the introduction to JavaScript with an example and today I am going to tell you in detail  How to Include Javascript Code in HTML Page and many more things that can help you in understand JavaScript easily. 
All right guys lets revise what we have learned in the past article, you saw me adding <script> </script> code at the bottom of the <body> tags. Today, I will show you in detail that what was the reason for adding the tags at the bottom and how can you add an external JS file.
How to Include Javascript Code in HTML Page
We have two methods to include the JS code in the Html file. 

Put the <script> tag in the Html head or body with Javascript code

<script type=”text/javascript”>
 alert(“I am learning JavaScript”);
</script>

 Put the script tag in the HTML head or bottom of the body with src attribute to the JavaScript file location. 

  <script type=”text/javascript” src=”Test.js”></script>
Best way to include JavaScript Code in HTML

You can add <script> tag in the <head> section of your HTML file, in the start of the <body> tag and also at the <bottom> of the body tag.

But I would advise you to add it at the end of the <body> tag. I will show you, why it should be at the bottom of the body tag.

(adsbygoogle = window.adsbygoogle || []).push({});

The HTML page always loads from top to bottom & if your JS file will be present in <head> or opening of the <body> tag, then browser will run JavaScript first, before loading any of the content and it will leave a negative impact on your webpage.

As you can see in below image that I have added <script> tag at the start of <body> tag and add a new tag of <h1> and <p> to know how code works.

Save these file and press ALT + B to execute this code.

You will notice that as you see in the picture  underneath that only <script> tag alert comes up first without loading the rest of page. 

(adsbygoogle = window.adsbygoogle || []).push({});

But once I click at ok then it has loaded the rest of the page now, as indicated in the image here:

If I put the <script> at the bottom of the <body> tag and you can see image down:

Now save it go again to the browser and reload the page.
Content will appear first and then we will have the alert form.
So, placing JavaScript code at the end of <body> tag is the best way.

Where To Add Your JavaScript File
So, short...

Top