How to place JavaScript within HTML

Web programming topics
Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to place JavaScript within HTML

Post by Saman » Fri Sep 10, 2010 8:13 pm

JavaScript code can be inserted either in the head of the document (between the <head> and </head> tags) or in the body (between the <body> and </body> tags). However, it is a good idea to always place JavaScript code in the head if you can, like so:

Code: Select all

<html><head><title>My Page</title>
<script language="javascript" type="text/javascript">
function myFunction() {
    alert('Hello world');
}
</script>
</head>
<body>
<a href="javascript:myFunction();">Click here</a>
</body>
</html>
Since the head loads before the body, placing code in the head ensures that it is available when needed. For example, the following code will work once the page has completely loaded, but if a user manages to click the link before the function has loaded they will get an error. This can easily become an issue if the page is large or slow to load.

Code: Select all

<html><head><title>My Page</title>
</head>
<body>
<a href="javascript:myFunction();">Click here</a>
<script language="javascript" type="text/javascript">
function myFunction() {
    alert('Hello world');
}
</script>
</body>
</html>
Note: JavaScript can cause problems when used in tables. It may help to use JavaScript to create the entire table, or at least whole rows.
Post Reply

Return to “Web programming”