HTML and CSS Reference
In-Depth Information
Embedding and Loading JavaScript
JavaScript codes applied to a whole web page are usually declared in the (X)HTML head. JavaScript can also be used
locally in the body section of web documents. Those JavaScript codes that are used throughout the entire web site are
written in external files.
Generally, there are three ways to use JavaScript on web sites. They are discussed in the following sections.
Loading JavaScript from an External File
This technique is used when the same script applies to multiple documents. The file extension of external JavaScript
files is .js . The character encoding of these files is usually US-ASCII. JavaScript files encoded in other encoding
schemes might have interoperability problems. While UTF-8 is the perfect choice for (X)HTML web documents and
can be applied as the default character encoding in the text editor of any developer, care must be taken to encode
JavaScript files (similar to CSS files) in US-ASCII whenever possible.
External JavaScript files should contain JavaScript code exclusively (Listing 6-25). The script tags must also be
avoided (Listing 6-26)!
Listing 6-25. JavaScript Code in the Markup
<script type="text/javascript">
document.write("Nice coding");
Listing 6-26. The Same Code in an External .js File
document.write("Nice coding");
External JavaScript files can be loaded with the src attribute on the script element. 1 Listing 6-27 shows an
Listing 6-27. Loading JavaScript from an External File
<script type="text/javascript" src= " scripts/click.js "></script>
This embedding is commonly used for the scripts loaded in the document head and any scripts that are too long
to write directly into the markup. Alternate style selectors, font resizers, and hidden layer controller scripts are some
examples for this approach.
Inline JavaScript
JavaScript can also be written directly in the markup as the content of the script element. Assume we have the JavaScript
function shown in Listing 6-28 and variables in Listing 6-29 either in the document head or in an external .js file.
Listing 6-28. A Short JavaScript Function
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
1 In the early days of the Web, the language="javascript" attribute-value pair was used on the script element, which was later
deprecated in favor of type="text/javascript" .
Search WWH ::

Custom Search