Where to Place JavaScript in an HTML Page
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:
<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.
<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.