JavaScript Where To

« Previous Next Chapter »

JavaScripts can be put in the body and in the head sections of an HTML page.


Where to Put the JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, or at a later event, such as when a user clicks a button. When this is the case we put the script inside a function, you will learn about functions in a later chapter.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

It is a good practice to put all your functions in the head section, this way they are all in one place and do not interfere with page content.

Example

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>

</head>

<body onload="message()">
</body>
</html>

Try it yourself »

Scripts in <body>

Scripts placed in the body section are often used to display page content while the page loads.

Example

<html>
<head>
</head>

<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>

</body>

</html>

Try it yourself »

Scripts 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.

Example

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>

</head>

<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>

</body>

</html>

Try it yourself »


Using an External JavaScript

JavaScript can also be placed in external files.

External JavaScript files often contains code to be used on several different web pages.

External JavaScript files have the file extension .js.

Note: External script cannot contain the <script></script> tags!

To use an external script, point to the .js file in the "src" attribute of the <script> tag:

Example

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

Try it yourself »

Note: Remember to place the script exactly where you normally would write the script!


« Previous Next Chapter »