Monday, June 4, 2012

Java Script Beginner Tutorial 3 : Where to place JS

There are different ways, we can place Java Script code inside web page. These are as follows
JavaScript in <body>
JavaScript in <head>
Using an External JavaScript


JavaScript in <body> :
Java Script code can be placed in <body> tag. It is placed at the bottom of the page to make sure all the elements are loaded completely. If Java Script code executed before entire page loaded then it may cause problem, e.g trying to change content of some element ( say <p> ) , which is not loaded yet, can cause problem. For example


<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>


If we place <p> tag after Java Script code then definitely it cause problem.


JavaScript Functions and Events :
If we want to execute a JavaScript when an event occurs, such as when a user clicks a button then we 'll put the script inside a function. Functions are normally used in combination with events. For example, in following code, JS function named "myFunction" 'll be called on button click event. ( This is also example of Java Script in <head> )


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
document.getElementById("content").innerHTML="Edited using JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<button type="button" onclick="myFunction()">Click Me !!!</button>
</body>
</html>


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.


Using an External JavaScript :
JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag. For example


<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="myScript.js"></script>
</body>
</html>


The script will behave as it was located in the document, exactly where you put it.

No comments:

Post a Comment