Placing JavaScript
JavaScript can be placed in the head and in the body sections of an HTML document.
No matter were the JavaScript code is placed in the document, it will be executed immediately while the page loads into the browser. The only way to avoid this is to place the JavaScript inside of a function.
Scripts Within <head>
JavaScript can be placed within the <head>
section of an HTML document using either the internal or external method. The following example shows an internal JavaScript within the <head>
element:
<html>
<head>
<script>
document.write("Hello from JavaScript");
</script>
</head>
<body>
content goes here
</body>
</html>
Scripts Within <body>
JavaScript can be placed within the <body>
section of an HTML document using either the internal or external method. In general, it is best to place code within the <body> section when it is not inside a function, or if the script writes page content. The following example shows JavaScript writing a message within the body:
<html>
<head>
</head>
<body>
<script>
document.write("Hello from JavaScript");
</script>
</body>
</html>
Sometimes there are cases when it is best to place JavaScript code within the <head>
section and the <body>
section. The following example shows JavaScript within both sections:
<html>
<head>
<script>
function message()
{
document.write("Hello from 'head'<br />");
}
</script>
</head>
<body>
<script>
message();
document.write("Hello from 'body'<br />");
</script>
</body>
</html>
This produces the following result: