Methods to use JavaScript

Welcome to the Javascript tutorial, and today we will discuss methods to use javascript. Before that you should know how to enable javascript, the best part of javascript is “ It can be used anywhere in web page”.

Methods to use JavaScript

Don’t worry, we have to remember only two places:

<head> tag

<body> tag

Note: If you don’t want to include javascript code with Html, then you can create external script, and include in your web page.

We will recommend you to use external javascript method to implement, and the reason for it:

Separate codes for html and javascript are easy to refer.

It will give a professional look to your html and javascript code.

It will load faster(cached).

You can reuse the external javascript as per the need.

Now we will see methods to implement javascript one by one with examples.

JavaScript in Head tag

Now we will see one of the methods to use javascript, and it is in the head section of the Html.

<html><head><script>function asksharplesson() { document.getElementById("changeit").innerHTML = "You have used js in head tag.";}</script></head><body><h2 id="changeit">Methods to use Javascript</h2><button type="button" onclick="asksharplesson()">Try it</button></body></html>

When you will run above code, then you will get two results:

JavaScript in body tag

Now we will see how we will use JavaScript in a body element. We will use the same example as we used above. Just cut the <script> tag and paste it in the body tag.

When you will run the program you will get the same result(instead of head tag, body tag will be shown), We deliberately used the same example to show you the ease of placing script in html pages.

External JavaScript

Let’s see how to use external JavaScript in our html documents, again we will use the same example, because we want to show you methods to use JavaScript and it will be easy for you to grasp same example.

We just cut the JavaScript code from the script, and paste it into the normal text editor and named it “ externalsharplesson.js” , here js is JavaScript extension. Now include that external JavaScript in your html page using script tag as we did above.

When you will run this program, you will get the same result, which we got in the above examples.

Conclusion

We have just finished methods to use JavaScript with simple examples, we just explained the methods to implement it, there are a few terms you must be wondering what it is? Don’t worry we will cover it in the relevant topic.