Placement JavaScript to HTML File
Placement JavaScript to HTML File
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
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.
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
JavaScript
in <head>...</head> section
If you 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 as follows –
Javascript
Code
Output
Before
clicking Click me button the output is-
After
clicking Click me button the output is-
JavaScript
in <body>...</body> section
If you 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. In this case, you
would not
have any function defined using JavaScript.
JavaScript
Code
Output
JavaScript
Code
Output
After Click on Click me Button
JavaScript
in <body> and <head> Sections
You can put your JavaScript code
in <head> and <body> section altogether.
Javascript
Code
Output
JavaScript
in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of a
site.
You are not restricted to be maintaining 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.
Javascript
Code
This Code save it files name.js
And
Put the link own this Code.
Output
First
Look this View
Click on Try it Button that view
saying
No comments: