Where to put Javascript
Posted by David on March 7th, 2007 filed in JavaScriptJavaScripts in the body section will be executed WHILE the page loads.
Scripts will be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<html>
<head>
<script type="text/javascript">
….
</script>
</head>
<head>
<script type="text/javascript">
….
</script>
</head>
JavaScripts in the head section will be executed when CALLED.
When you place a script in the body section it generates the content of the page.
<html>
<head>
</head>
<body>
<script type="text/javascript">
….
</script>
</body>
<head>
</head>
<body>
<script type="text/javascript">
….
</script>
</body>
Using an External JavaScript
Note: The external script cannot contain the <script> tag!
<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>