How to include Javascript on a web page

By Eric Downing. Filed in html, Programming, Web Design  |  
TOP del.icio.us digg

There are three ways to include Javascript files on a website. You can use scripts placed in the head element, scripts placed within the body element or you can include an external file.

The <script> tag is used to contain the Javascript code when you are placing it within the web page.

Example of code within the <head> tag:

 <!DOCTYPE html>
<html>
<head>
<title>Javascript in Head tag</script>
<script language="javascript" type="text/javascript" >
     document.write("Hello, World!");
</script>
</head>
<body>
</body>
</html>

When you are expecting to output directly into the page it is helpful to place the script in the
<body> tag.

<!DOCTYPE html>
<html>
<head>
<title>Javascript in Body tag</script>
<script>

</script>
</head>
<body>
<script language="javascript" type="text/javascript" >
  document.write("Hello, World!");
</script>
</body>
</html>

And when you are including an external script like jQuery or a custom script, you will use an
tag in the head with a src identifier to specify the file. Where you might reference the file in an onload or some other scripting within the page.

<!DOCTYPE html>
<html>
<head>
<title>Javascript in External file</script>
<script language="javascript" type="text/javascript" src="somefile.js" > </script>
</head>
<body onload="callsomefile();" >
</body>
</html>

There is also the possibility that someone will have turned off Javascript and this is where the <noscript> tag can be used to either display the site designed with no scripting involved or inform the user that they cannot use the site unless Javascript is enabled.

Tags: , ,

Leave a Reply