|
Incorporating JavaScript into your HTML pages
Including scripts in HTML is simple. Most scripts are contained inside a <SCRIPT> container tag. In other words, on opening <SCRIPT> tag starts the script and a closing </SCRIPT> tag ends it:
This code runs as soon as the browsers reads it. On the document it displays the message: This document last modified on: (Date of the Document last modification) Where can you put a script? Anywhere in the <HEAD> or <BODY> of your HTML document. You'll learn as we progress that there are preferred locations for certain scripts, depending on what you are trying to accomplish. Note that you can put multiple scripts in your page.
JavaScript code in a <SCRIPT> is executed once, when the HTML file that contains it is read into the web browser. A program that uses only this sort of static script cannot respond dynamically to the user. More dynamic programs define Event Handlers that are automatically invoked by the web browser when certain events occur - for example, when the user clicks on a button within a form. Because events in client-side JavaScript originate form HTML objects (like buttons), Event Handlers are defined as attributes of those objects. In order to define JavaScript event handlers as part of HTML object definitions, JavaScript extends HTML by adding event handler attributes to various HTML tags. The <SCRIPT> tag can take optional attributes which determines how the JavaScript script in question is incorporated into the HTML file.
The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements you can write entire JavaScripts in one line. You can fit an entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it. Here the "script" is inside the <INPUT> tag. When you click the button, the "script" that appears after onClick, the alert() function, runs. An "onMouseOver" example with the script within an HTML tag. An example illustrating Methods 1 & 2 simultaneously. Modular Event HandlersWhich of these is easier to read?
At first this may seem convenient, but remember the KISS principle. What if you had 10 buttons or onMouseOver all using the same "event_handler_code" . If you had to make a change in the "event_handler_code" you would to have to make the change in 10 different places. Not a good way of doing something. Of course, this example assumes that the function subTotal() has been defined somewhere earlier in the page, such as embedded into the <HEAD> section or included via an external .js file which is discussed below. That's why we want to segregate scripts from HTML. Attributes for the <SCRIPT> tag
If you are using JavaScript you do not have to specify the LANGUAGE attribute. By default the LANGUAGE is JavaScript. However, if you want to specify a specific JavaScript version such as 1.2 then you would specify the LANGUAGE="JavaScript1.2". If you are going to use another language such as VBScript then you need to tell the browser what Interpreter to use. The VBScript language is built-in the Microsoft IE browsers. NOTE: VBScript does not work in the Netscape browsers. If the browser is not compatible with the specified version of JavaScript, it simply ignores the script following the <SCRIPT> tag.
Including JavaScript programs directly in the HTML files can be convenient for small scripts and basic HTML pages, it can quickly get out of hand when pages require long and complex scripts or when the code and information is used throughout the website. To make development and maintenance of HTML files and JavaScript scripts easier, the JavaScript specification includes the option of keeping your JavaScript in separate files and using the SRC attribute of the <SCRIPT> tag to include the JavaScript program in an HTML file
One of the benefits of this approach is that your script are automatically hidden from other browser that don’t support JavaScript. Your external script can contain any code you like, but it usually contains functions. Functions provide the modularity we seek in a programming architecture. The format of the .js file is simply the naked script with no HTML tags present. For example, consider this page made up of two files: one is the HTML source and the other is the JavaScript source.
Now you can see why external files allow for the possibility of creating portable functions. Imagine that you authored the calcShipping() function. Suppose it only required two incoming parameters, shipment weight and the destination state. The function itself then did all the dirty work -- translating the state abbreviation into a shipping zone and calculating the rate based on some representation of the shipping rate chart which you've built into the function. Once done the function simply returns a number reflecting the cost. As long as this function is coded portably; that is, relies only on internal local variables to do the work, you could distribute this function to anyone who wanted the ability to calculate shipping rates. In fact, others wouldn't even need to copy the function from you. They could simply link to it on your server, should you be in such a generous mood:
Such a setup would be highly modular and portable -- if you had to change the rate table, you simply modify this function and every site which links to it will automatically reflect the new rates. Even if you are not ready to distribute your modular functions globally, this type of portability is useful even within your own site, since any page on your site can easily access common functions. And changes to these functions are immediately reflected on every page which uses them. From a people perspective, the JavaScript guru of your team can play with calcShipping() all day without needing to see any of the HTML -- and vice versa for your HTML designers. While the SRC attribute goes a long way to helping segregate programming language from markup tags, it is no panacea. There remains one large, sticky problem, and those are Event Handlers. Note: At the same time, though, this technique requires an additional server request and server access, which may be problematic on a slow server or across a slow connection to the Internet. Check out the source for menu.htm, where is the script that contains goPage(this.form)? menu.js contains the function. Even the browser doesn't display the menu.js scripts and functions when you view the source, the menu.js scripts and functions are really stored in the browser's memory ready for use. If an individual wanted to view the "missing" scripts, all the individual would have to do is just download the file, in this particular case menu.js happens to be in the same directory. Before using code within a source file from within the HTML file it is recommended that a test is made to ensure that the source file has actually loaded:
The variable loaded gets changed from false to true if library.js is "loaded" and ready to go. If your program uses a number of JavaScript files, it can be more efficient to combine them into a single compressed JAR (Java ARchive) file that can be loaded over the network. NOTE:
A JAR archive is simply a common ZIP file with some additional manifest information added. Netscape provides a free tool that allows developers to create JAR archives. One of the most important uses of archives is attaching digital signatures to scripts.
Of course, an immediate problem crops up with this type of <SCRIPT> container: Browsers that don’t support JavaScript will happily attempt to display or parse the content of the script. In order to avoid this, use the following approach using HTML comments:
These comments:
ensure that other browsers will ignore the entire script and not display it because everything between <!—and --> should be ignored by a standard browser. Of course, if two users were to view the source code of the document, they would still see the script. Probably 99+% of the all browsers support JavaScript today. So this particular problem is not an issue anymore. Here a brief comment is included after each variable declaration to explain what the variable is and how it will be used. These comments make it much easier to decipher what is happening later on in the program. Because variable declaration is done first, these comments are also all grouped together in one place that is easy for someone reading the code to refer back to.
The following is incorrect:
--> on its own is not a valid JavaScript comment tag. The following is correct:
To make a script easier to read make use of command blocks. The simple process of using indentations greatly improves readability and being able to follow the flow of a program. Commenting & Command Blocks will in the long run definitely help improve your scripting.
|