It’s a common question when you start learning JavaScript and wonder that where should you put your JavaScript code in HTML file. I have faced it. Many others have as well. Let’s go through that amazing JavaScript script tag one by one and decide together.
First of all, all the JavaScript code must be inserted between script tag. I know, I know. That is really basic information but for those who don’t know how JavaScript works, I needed to tell them. Let me show the code as well.
document.getElementById("example").innerHTML =
"All JavaScript code must be written in script tag, like this code.";
PLEASE NOTE: Although JavaScript is the default scripting language in HTML, there are many old JavaScript examples in which you’ll see type attribute:
Now, let's look at the following examples for adding script tag to HTML body tag.
REMEMBER to place JavaScript code at the bottom of the HTML code, right before closing the body tag. When the browser interprets and displays the page, the JavaScript code takes longer time to interpret. So if you place the code at the bottom, it'll improve the display speed.
Now, apart from above methods to add JavaScript code, there is one more and that is to add external javascript file to the HTML code. All you do is write down the same code which is in between the script tag to a different file and name it as "filename.js". Just add ".js" at the end to make it a JavaScript file. for e.g.
// This is our .js file code
function Function2() {
document.getElementById("example2").innerHTML = "Script tag is in body tag.";
}
REMEMBER that external .js file does not contain any script tag itself.
Now add that file to the HTML code like this..using script tag.
You can place this line between the head tag or body tag.
Now, that brings us to our main question of what is the best way to add js code to HTML code.
The answer is "external JS files".
Because...
It separates the HTML code and JS code.
It's really easy to read both files and maintain easily.
It's really convenient when you want to use the same JS code to many webpages.
Browser caches the JS files separately. So, it can really speed up the page loads.
You can even use a .js file from external references like from the web... for e.g.
script tag