JavaScript tutorial - Adding JavaScript to a page

Navigation

Skip navigation.

Site search

Site navigation

JavaScript tutorial

Printing

Other tutorials

Adding JavaScript to a page

You can add a script anywhere inside the head or body sections of your document. However, to keep your document well structured there are some basic guidelines:

Adding a script to the page

To insert JavaScript into a web page, use the <script> tag. You should use the type attribute to specify the type of script being used, which in the case of JavaScript is text/javascript. It is also possible to the language attribute to say what JavaScript version you are using. In practice, this number means very little to browsers. They may claim to support a specific version, but will have vastly different capabilities. All JavaScript supporting browsers currently in use will support a level of JavaScript equivalent to JavaScript 1.2 (represented as "javascript1.2") or higher, so this is what I will teach you in this tutorial.

Browsers will generally choose an arbitrary version number that they will claim to support, and will run any script that has either no language version number, or a version equal to or lower than the one they claim to support. Since the language is so unreliable, you should generally omit this attribute, although it is common to see scripts using it. Your script can then detect if the browser is capable of running your script, and it can do this a lot more accurately than the version number can.

This is an example of a script tag, used to include a script in your page:

<script type="text/javascript">
//JavaScript goes here
</script>

If your script is incapable of providing its own fallback, but it is needed to access the page, you should include support for non-JavaScript browsers by using:

<noscript>
  <p>This will not be displayed if JavaScript is enabled</p>
</noscript>

Using comments

Comments allow you to leave notes to yourself and other people in your script, and are useful as a reminder of what the script is doing and why. The double slash indicates a single line comment. Everything after it on the same line will be ignored by the script engine. The slash-asterisk indicates a block comment. Everything after it will be ignored by the script engine until an asterisk-slash is encountered.

<script type="text/javascript">

//This is a single line comment

/* This is a
block comment */

</script>

Using external script files

You can also use a separate header file to contain the JavaScript (usually *.js) making it easy to share across pages:

<script src="whatever.js" type="text/javascript"></script>

When using header files, if you put any script code in between the <script ...> and </script> tags, it will only be executed if the browser does not support header files (assuming it does support the version of JavaScript shown in the language attribute, if you used one). In reality, this is only for very old browsers that are not used at all any more, so there is no need for anything to be put there.

Scripts in header files are executed as if they were in the main page. If the script referances any external files, such as images, the addresses it uses are relative to the main page, not the script URI.

Commenting out your scripts

This is not needed any more. All current browsers are aware of script tags, and how to treat their contents, since they have been part of HTML since HTML 3. Browsers that do not understand HTML 3 or scripts (these are virtually never used now) will display the script as if it was the content of the page. You can hide the script from them by commenting out your script with standard HTML comments. Browsers that understand script will simply ignore these comments, and will just interpret the script within them. The opening comment is ignored as if it were a normal single line JavaScript comment. The closing comment will not, so it needs to have a JavaScript comment put before it:

<script type="text/javascript">
<!--

//JavaScript goes here

//-->
</script>

These HTML comments should not be used if you are using an external script file, and are not to be used anywhere else in your scripts.

Dealing with XHTML

Note that when I talk about XHTML, I am talking about pages that are served using a content type of application/xhtml+xml - the majority of pages that use XHTML markup are actually served as text/html and as a result are correctly treated as HTML, not XHTML.

The rules in XHTML are different. Script tags are not treated as being special. Their contents are treated as any other part of XHTML, so various operators can be misinterpreted as part of the markup. To avoid this, it is best to put all scripts in external script files so that they do not interfere with the page itself. If you feel the need to put something directly on the page, you can declare it as CDATA (the default for script contents in normal HTML):

<script type="text/javascript">
<![CDATA[

//JavaScript goes here

]]>
</script>

If you feel the compulsion to comment out your script in XHTML, you must use a more ugly structure to contain your scripts. Again, this really is not needed, since browsers that do not understand script also do not understand XHTML, but in case you want to use it (maybe you are serving it as XHTML to some browsers, and HTML to others), this is what to use:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

//JavaScript goes here

//--><!]]>
</script>

Controlling when the script is activated

By default, any script you write will be processed as the document loads. For example:

<script type="text/javascript">
var myVariable = 'Hello';
window.alert(myVariable);
//as the document loads, a message box saying 'Hello' will be displayed
</script>

Sometimes, this may be undesirable and it may be better to write functions (see the section on Writing functions) and activate them later.

To activate JavaScript, you can use HTML events. Modern browsers can detect a vast number of events on most elements. Older browsers are more limited and can only detect the standard set of events on specific elements. The ones that will work in all browsers I have tested are:

input, textarea, select
onclick, onkeydown, onkeyup, onkeypress, onchange, onfocus, onblur, etc.
form
onsubmit, onreset
a
onclick, onmouseover, onmouseout, onfocus, onblur
body
onload, onunload

Check with the HTML specifications on the W3C site for more details. 'a' elements can also detect onmousemove in all current browsers, but not some of the older browsers that are not used any more. For some of these older browsers, such as Netscape 4, it is possible to compensate using a combination of onmouseover, onmouseout and then document.captureEvents and onmousemove on the body (see the section on Event information). The Event information and more advanced DOM events chapters of this tutorial show how to listen for more event types, and obtain information from them.

These are some examples of using events (shown here using traditional inline event handlers - later on in this tutorial, I will show you alternative ways to attach events to elements that will not require you to alter your HTML):

<a onmouseover="name_of_function(params)" href="somepage.html">
<input onkeypress="myVariable = 2;startTest();">
<select onchange="self.location.href = this.options[this.selectedIndex].value;">
<body onunload="window.alert('bye')">

Another way of making HTML activate JavaScript is to use <a href="javascript:name_of_function(params)"> but in general it is best to use events, so the link can provide an accessible alternative if JavaScript is not available (the event handler can prevent the browser from using the link normally if scripting is available).

In all these cases, the script is contained within HTML attributes, and is subject to the normal rules of HTML entities. If you need to put quotes in the script in between the quotes in the html, use the HTML entity &quot; or &#34; for " style quotes or if your quotes in the HTML are done using the ' quotes (which is unusual ...), you can use &#39; to represent these in the script. If you need to include < or > operators, you should use the &lt; and &gt; entities.

Last modified: 20 November 2009

  1. Previous
  2. Next
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.