Javascript: the Beginning - Putting JavaScript in its Place
(Page 3 of 4 )
Having a similar name to a big-shot like Java has given JavaScript a big head. Quite frankly, it needs to be put in his place. But where is that place you ask? Hold on a second and I'll show you.
There are three places you can put JavaScript. Well, there's also a fourth if your boss really ticks you off, but that's for another tutorial.
Head Section: This is for scripts that contain functions and need to be loaded prior to the function being called.
Body Section: This is for scripts that need to be executed when the page loads.
Externally: If you have a script that runs across multiple pages and do not wish to write the script on each page, you can store the script externally.
It's worth noting, in case this list gives you the wrong idea, that you can use multiple scripts throughout your page.
Here are some examples of each placement:
<html>
<head>
<script type="text/javascript"> // don't forget this line
YOUR SCRIPT HERE //this is where your script would go
</script>
</head>
<body>
</body>
</html>
The above is an example of placing a script in the HEAD section.
<html>
<head>
</head>
<body>
<script type="text/javascript"> // don't forget this line
YOUR SCRIPT HERE //this is where your script would go
</script>
</body>
</html>
That was an example of storing scripts in the BODY section. And lastly:
<html>
<head>
<script src="nameofthescript.js"></script>
</head>
<body>
</body>
</html>
The above shows you how to call a script that is external. Note that where you place this tag depends on what type of script it is. If it needed to be loaded with the page, you would have placed it in the body section instead. Also be aware that the external script can not contain the <script> tag.
One more thing. This is how it looks to use JavaScript in multiple sections.
<html>
<head>
<script type="text/javascript">
YOUR SCRIPT HERE
</script>
</head>
<body>
<script type="text/javascript">
YOUR SCRIPT HERE
</script>
</body>
</html>
Next: Variables >>
More JavaScript Articles
More By James Payne