JavaScript Where to
JavaScripts can be put in the <body>
and in the <head>
sections of an HTML page.
JavaScript in <body>
The example below writes the browser name into an existing <p>
element when the page loads by using the appName
property of the object navigator
.
Note that the JavaScript is placed at the bottom of the page to make sure it is not executed before the <p>
element is created.
JavaScript Functions and Events
JavaScripts in an HTML page will be executed when the page loads.
This is not always what we want.
Sometimes we want to execute JavaScript script when an event occurs, such as when a user clicks on a button.
When this is the case we can put the script inside a function.
Events are normally used in combination with functions (like calling a function when an event occurs).
Script in <head>
and <body>
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page.
This way they are all in one place and do not interfere with page content.
Demonstration
The following demonstration shows how the script of HTML and JavaScript is displayed on the Web.