JavaScript Placement - Java Script

What is JavaScript-placement?

JavaScript code can be added anywhere in HTML document ,however the commonly used ways to include JavaScript in an HTML file are explained below −

  • Script in <head>...</head> section.
  • Script in <body>...</body> section.
  • Script in <body>...</body> and <head>...</head> sections.
  • Script in an external file and then include in <head>...</head> section.

How to include JavaScript in your HTML document?

Lets see..

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

If you need script to be run on certain event, like clicking on somewhere an action to be done , then you will place that script in the head as follows −

The above code will produce the result as follows −

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

If you want a script to run when page loads, so that the content in the page is generated by the script, then the script goes in the <body> portion of the document. For this, you will not have any function defined using JavaScript. See the code below-

This code will produce the following results −

JavaScript in <body> and <head> Sections:

Your JavaScript code can be added in <head> and <body> section at a time as follows −

This code will produce the following result −

JavaScript in External File:

When you start working with JavaScript more extensively, you will come to know that you will be reusing identical JavaScript code on multiple pages of a site.

You need not to repeat identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

Below is the example that explains, how you can include an external JavaScript file in your HTML code using script tag and its src attribute.

To use JavaScript from an external file source, First write all your JavaScript source code in a simple text file and save it with the extension ".js" and then include that file as shown above.

For example, you can keep the following content in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Java Script Topics