Open Directory Site JavaScript Tutorials

ASP | XML | VBScript | JavaScript | ADO | CSS | XMLDOM | PHP | Operating Systems

Home >> JavaScript >> JavaScript Where To

JavaScript Where To

 

Where to put the JavaScript

Scripts 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, other times when a user trigger an event.

Scripts in the head section: Scripts to be executed when they are called or when an event is triggered, goes in the head section. When you place a script in the head section you will assure that the script is loaded before anyone use it.

<html>

<head>

<script language="JavaScript">

some statements

</script>

</head>

Scripts in the body section: Scripts to be executed when the page loads, goes in the body section. When you place a script in the body section it generates the content of the page.

<html>

<head>

</head>

<body>

<script language="JavaScript">

some statements

</script>

</body>

Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

<html>

<head>

<script language="JavaScript">

some statements

</script>

</head>

<body>

<script language="JavaScript">

some statements

</script>

</body>

How to use external script

Sometimes you might want to run the same script on several pages, without writing the script on each and every page. To simplify this you can write the script in a external file, and save it with a .js file extension. Like this:

document.write("This script is external")

Save the external file as xxx.js

-The filename can not contain more than 8 letters

-The external script can not contain the <script> tag

Now you can call this script, using the "src" attribute, from any of your pages:

<html>

<head>

</head>

<body>

<script src="xxx.js">

</script>

</body>

</html>

Remember to place the script exactly where you normally would write the script

 

Examples

1.Script that contains functions goes in the head section of the document, then we can be sure that the script is loaded before the function is called.

Coding

<html>

<head>

<script language="JavaScript">

function message()

{

alert("This alert box was called with the onload event")

}

</script>

</head>

<body onload="message()">

</body>

</html>

2.Execute a script that is placed in the body section.

Coding

<html>

<head>

</head>

<body>

<script language="JavaScript">

document.write("This message is written when the page loads")

</script>

</body>

</html>

Output

This message is written when the page loads

3.How to access an external script.

Coding

<html>

<head>

</head>

<body>

<script src="xxx.js">

</script>

</body>

</html>

Output

This script is external

Cheap Web Hosting Articles - Web Site Design & Web Hosting Tutorials - Domain Hosting