Lecture 2 – JavaScript Placement

You can place JavaScript anywhere on your HTML document. However, the following are the best and preferred ways to include JavaScript.

  • Adding script tag within in tags.
  • Adding script tag in tags.
  • Adding script tag both in and tags.
  • Writing script in an external JavaScript file which you can include in head or body section.

Placement in Head Section

If you want to initiate an event using JavaScript, you will add JavaScript in the head section. Look at the following example.




    JavaScript Syntax
    
       
           function myName() {
              alert("Martin")
           }

    
        
</head>
<body>
        <input type = "button" onclick = "myName()" value = "My Name" />
</body>
</html>

You will get the following result when the code is implemented.

Placement in Body Section

If you want to the script to generate content in the webpage, you will place JavaScript in the Body section.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript Placement</title>
</head>
<body>
        
            document.write('Hello World!')
        

        <p>This is how you add JavaScript to Body Section.</p>
</body>
</html>

The output of the above code is as under.

Placement in Body and Head Sections

It is possible to include JavaScript in the Head and the Body Section at the same time. Take a look at the following example.

<html>
   <head>
        
       
            function myName() {
               alert("Martin")
            }
 
     
 
         
      </script>
   </head>
   
   <body>
      
         
            document.write("Hello World")
         
      
      
      <input type = "button" onclick = "myName()" value = "My Name" />   </body>
</html>

You will get the following result.

Including External JavaScript File

It is also possible to include external JavaScript file using the script tag and the source (src) attribute. First, you will have to create a simple file with .js extension and write all your JavaScript on that file.

The following example explains how you can add the external JavaScript file to your HTML document.


   
 
         
   
   
   
      
         
      
      
      <input type = "button" onclick = "myName()" value = "My Name" />   </body>
</html>

The browser will produce the following result.

In the next lecture, we will study JavaScript Variables