Attaching JavaScript.

There are three ways to attach JavaScript into an XHTML page.

The best way of attaching JavaScript is to place all of the JavaScript into a separate file and to then link that file into the head of your web page using the following code:

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

That code added immediately before the </hhead> tag will load the JavaScript along with the web page. It is then simply a matter of ensuring that the JavaScript is written in such a way that it will attach the appropriate event handlers into your page content after those parts of the page finish loading.

You can also attach JavaScript into other places in the web page by using the same code, however the way that XHTML works with JavaScript it is much simpler to include all of the JavaScript into the one file attached to the head of the page rather than placing sections of JavaScript code at different places in the page.

The second way of attaching JavaScript into XHTML is mostly useful for when you are testing your page since it nests the JavaScript code within the XHTML of the page itself. You code embedded JavaScript like this:

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

This allows you to test the JavaScript and make alterations to both the XHTML and JavaScript in the one place while testing before moving the JavaScript out into its own separate file.

Note that this only works exactly like this if you actually process the page as XHTML. If you process the page as HTML instead then some browsers may not recognise the CDATA tag correctly. To cater for those browsers you can enclose the start and end parts of that tag inside JavaScript comments.

The third way of adding JavaScript into your XHTML is to add the event handlers directly into the XHTML tags that those events are to be attached to. This method of attaching JavaScript into XHTML is not recommended as it means that you are making the two more dependent on each other and increasing the chance of needing to change all of the XHTML for your entire site in order to apply a minor change to the JavaScript processing.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow