Methods to include JavaScript in HTML documents

In an HTML document we can write JavaScript code in Head or body section and also we can write JavaScript into external file with .js extension.

1. JavaScript in <head>...</head> section :

We can put the JavaScript code inside the <head> tag within the <script> tag. Sometimes page content depend on this JavaScript code, for example if we want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head tag. For example :
<html>
<head>
  <script>
    function hello() {
      alert("Hello world From mycsnotes.com");
    }
  </script>
</head>
<body>
  <input type="button" onclick="hello()" value="Click Here" />
</body>
</html>
Output :



2. JavaScript in <body>...</body> section :

We can put the JavaScript code inside the <body> tag within the <script> tag. Writing  JavaScript code at end of the body section will improve the page loading speed, because HTML content loading is not blocking JavaScript code. Although if we need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. For example :
<html>
<head>
  <title>JavaScript</title>
</head>
<html>
<body>
  <script type="text/javascript">
    document.write(" Hello world !!.");
  </script>
</body>
</html>
Output :



3. Javascript in External file :

We can write the JavaScript code on to an external file with ".js" extension, and link it with the html document. External scripts are very useful when the same code is used in many different web pages. By using src attribute and the path of the js file as its value, we can link an external JavaScript file within the html document. Example :

JavaScript File :
function hello() {
  alert("Hello world From mycsnotes.com");
}
Html File : 
<html>
<head>
  <script src="hello.js"></script>
</head>
<body>
  <input type="button" onclick="hello()" value="Click Here" />
</body>
</html>


Next Topic :