Starting JavaScript Part 2:Adding JavaScript to a Web PageHere we are going to look at how you add scripts to your web pages, how and when the scripts execute and where to place those scripts. To insert JavaScript into a web page you use the script tags as shown below: <SCRIPT> In order to hide the script from browsers that don't understand JavaScript the script code is usually enclosed in comment tags. The comment tags are here shown in red: <!--This is a comment enclosed in tags //--> The code would now look like this:
<SCRIPT>
<!-- JavaScript code goes here //--> Notice the position of the comment tags they are inside the script tags. A common mistake is to enclose everything in comment tags which means your script gets completely ignored. In addition for browsers that don't understand JavaScript (not many today) what will they see.. Not the results of the script! To cater for these it is normal to use the NOSCRIPT tag as follows: <NOSCRIPT> Specify the Scripting LanguageAlthough we are only discussing JavaScript here it is also possible to use VB script (Microsoft only). Most web browsers will use JavaScript as the default scripting language but you should specify it anyway. There are two methods of doing this: You can specify it inside the opening script tag as follows:
<SCRIPT language="Javascript" type="text/javascript">
<!-- JavaScript code goes here //--> or you can specify it for the entire page by using a meta tag as follows: <META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript"> which is placed at the top of the document between the header tags.
Implementing ScriptsThere are two ways of implementing JavaScripts: Automatic and Triggered. AutomaticAutomatic scripts are run when the script is read by the web browser (see functions below) which means that the script must be located at the correct point in the HTML document. You place it at the beginning if it is to be executed first, and at the end if it is to be executed last etc. The example below shows script code inserted into the HTML document (highlighted) so that it prints out between two lines on plain HTML.
Click here and the script above will run in the frame below. Click here to reset
So the one way of running a JavaScript is to place it within the Script Tags in the HTML document at the location where you want it to run. Internal And External ScriptsThe script shown above was inserted directly into the HTML. This is an internal script and this form is commonly used for inserting small scripts. Large scripts are usually placed into an external file . This has the advantage that the script is:
Here is the example above replaced with an external script. Here is the html page:
and here is the external.js file
In this case the external file is only one line but it can be many hundreds.
|
|||||||
|