Create a Website
HTML
Dreamweaver
CSS Tutorial
JavaScript
FREE Domain!
Any web hosting you subscribe with DotEasy will get you a FREE domain name registration.
PLUS you get:
  • FREE Website Builder
  • FREE Blog
  • FREE Forum
  • FREE Photo Album
  • FREE Email Accounts
Get your FREE domain name today!
Home > JavaScript Tutorial
SSD Web Hosting with FREE Domain

The location of choice of header or body is very simple. If you want to have a script to be executed when they are called, or when an event is triggered, then, you will place that script in the header section. This ensures that the script is loaded before anyone uses it.

On the other hand, if you want the script to be executed when the page loads, then you will want to place the script within the body section.

JavaScript in the Header Section

Here's a basic example of adding JavaScript to the header section of the HTML document.

The JavaScript in the header section runs only when it is called or an event is triggered.

The Code

<html>
<head>
<script type="text/javascript">
<!--
function myscript () {
  alert("Hello!");
}
//-->
</script>

</head>
<body>
</body>
<html>

The onClick attribute in the code above is called JavaScript event handler. Event handlers allow you to detect when a given "event" has occured.

In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to the element.

The JavaScript in the Body Section

Here's a basic example of adding JavaScript to the body section of the HTML document.

The JavaScript in the body section runs as soon as page loads.

The Code

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
  alert("Hello!");
//-->
</script>

</body>
<html>

JavaScript in an External File

Sometimes you might want to run the same JavaScript on many pages or through the entire site, but don't want to rewrite the same code on every page.

To simplify this, you can write the code in an external file, and save the file with a .js file extension. Then, link to it from your HTML document.

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

Note: The external script cannot contain the <script> tag!

File: myjs.js

function myscript () {
  alert("Hello!");
}

The Code

<html>
<head>
<script src="myjs.js"></script>
</head>
<body>
</body>
</html>

Enjoy this tutorial?

1. Link to this page(copy/paste into your own website or blog):
2. Add this page to your favorite social bookmarks sites:
3. Add this page as your favorites. (Press Ctrl+D)