Section 13.2. Embedding Scripts in HTML


13.2. Embedding Scripts in HTML

Client-side JavaScript code is embedded within HTML documents in a number of ways:

  • Between a pair of <script> and </script> tags

  • From an external file specified by the src attribute of a <script> tag

  • In an event handler, specified as the value of an HTML attribute such as onclick or onmouseover

  • In a URL that uses the special javascript: protocol

This section covers <script> tags. Event handlers and JavaScript URLs are covered later in the chapter.

13.2.1. The <script> Tag

Client-side JavaScript scripts are part of an HTML file and are coded within <script>and </script> tags:

 <script> // Your JavaScript code goes here </script> 

In XHTML, the content of a <script> tag is treated like any other content. If your JavaScript code contains the < or & characters, these characters are interpreted as XML markup. For this reason, it is best to put all JavaScript code within a CDATA section if you are using XHTML:

 <script><![CDATA[// Your JavaScript code goes here ]]></script> 

A single HTML document may contain any number of <script> elements. Multiple, separate scripts are executed in the order in which they appear within the document (see the defer attribute in Section 13.2.4. for an exception, however). While separate scripts within a single file are executed at different times during the loading and parsing of the HTML file, they constitute part of the same JavaScript program: functions and variables defined in one script are available to all scripts that follow in the same file. For example, you can have the following script in the <head> of an HTML page:

 <script>function square(x) { return x*x; }</script> 

Later in the same HTML page, you can refer to the square( ) function, even though it's in a different script block. The context that matters is the HTML page, not the script block:[*]

[*] The alert( ) function used here is a simple way to display output in client-side JavaScript: it converts its argument to a string and displays that string in a pop-up dialog box. See Section 14.5. for details on the alert( ) method, and see Example 15-9 for an alternative to alert( ) that does not pop up a dialog box that must be clicked away.

 <script>alert(square(2));</script> 

Example 13-1 shows a sample HTML file that includes a simple JavaScript program. Note the difference between this example and many of the code fragments shown earlier in this book: this one is integrated with an HTML file and has a clear context in which it runs. Note also the use of a language attribute in the <script> tag; this is explained in Section 13.2.3.

Example 13-1. A simple JavaScript program in an HTML file

 <html> <head> <title>Today's Date</title> <script language="JavaScript"> // Define a function for later use function print_todays_date( ) {     var d = new Date( );                  // Get today's date and time     document.write(d.toLocaleString( ));  // Insert it into the document } </script> </head> <body> The date and time are:<br> <script language="JavaScript">   // Now call the function we defined above   print_todays_date( ); </script> </html> 

Example 13-1 also demonstrates the document.write( ) function. Client-side JavaScript code can use this function to output HTML text into the document at the location of the script (see Chapter 15 for further details on this method). Note that the possibility that scripts can generate output for insertion into the HTML document means that the HTML parser must interpret JavaScript scripts as part of the parsing process. It is not possible to simply concatenate all script text in a document and run it as one large script after the document has been parsed because any script within a document may alter the document (see the discussion of the defer attribute in Section 13.2.4.).

13.2.2. Scripts in External Files

The <script> tag supports a src attribute that specifies the URL of a file containing JavaScript code. It is used like this:

 <script src="/books/2/427/1/html/2/../../scripts/util.js"></script> 

A JavaScript file typically has a .js extension and contains pure JavaScript, without <script> tags or any other HTML.

A <script> tag with the src attribute specified behaves exactly as if the contents of the specified JavaScript file appeared directly between the <script> and </script> tags. Any code or markup that appears between these tags is ignored. Note that the closing </script> tag is required even when the src attribute is specified, and there is no JavaScript between the <script> and </script> tags.

There are a number of advantages to using the src attribute:

  • It simplifies your HTML files by allowing you to remove large blocks of JavaScript code from themthat is, it helps keep content and behavior separate. Using the src attribute is the cornerstone of unobtrusive JavaScript programming. (See Section 13.1.5. for more on this programming philosophy.)

  • When you have a function or other JavaScript code used by several different HTML files, you can keep it in a single file and read it into each HTML file that needs it. This makes code maintenance much easier.

  • When JavaScript functions are used by more than one page, placing them in a separate JavaScript file allows them to be cached by the browser, making them load more quickly. When JavaScript code is shared by multiple pages, the time savings of caching more than outweigh the small delay required for the browser to open a separate network connection to download the JavaScript file the first time it is requested.

  • Because the src attribute takes an arbitrary URL as its value, a JavaScript program or web page from one web server can employ code exported by other web servers. Much Internet advertising relies on this fact.

This last point has important security implications. The same-origin security policy described in Section 13.8.2. prevents JavaScript in a document from one domain from interacting with content from another domain. However, notice that the origin of the script itself does not matter: only the origin of the document in which the script is embedded. Therefore, the same-origin policy does not apply in this case: JavaScript code can interact with the document in which it is embedded, even when the code has a different origin than the document. When you use the src attribute to include a script in your page, you are giving the author of that script (and the webmaster of the domain from which the script is loaded) complete control over your web page.

13.2.3. Specifying the Scripting Language

Although JavaScript was the original scripting language for the Web and remains the most common by far, it is not the only one. The HTML specification is language-agnostic, and browser vendors can support whatever scripting languages they choose. In practice, the only alternative to JavaScript is Microsoft's Visual Basic Scripting Edition,[*] which is supported by Internet Explorer.

[*] Also known as VBScript. The only browser that supports VBScript is Internet Explorer, so scripts written in this language are not portable. VBScript interfaces with HTML objects the same way JavaScript does, but the core language itself has a different syntax than JavaScript. VBScript is not documented in this book.

Since there is more than one possible scripting language, you must tell the web browser what language your scripts are written in. This enables it to interpret the scripts correctly and to skip scripts written in languages that it does not know how to interpret. You can specify the default scripting language for a file with the HTTP Content-Script-Type header, and you can simulate this header with the HTML <meta> tag. To specify that all your scripts are in JavaScript (unless specified otherwise), just put the following tag in the <head> of all your HTML documents:

 <meta http-equiv="Content-Script-Type" content="text/javascript"> 

In practice, browsers assume that JavaScript is the default scripting language even if your server omits the Content-Script-Type header and your pages omit the <meta> tag. If you do not specify a default scripting language, however, or wish to override your default, you should use the type attribute of the <script> tag:

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

The traditional MIME type for JavaScript programs is "text/javascript". Another type that has been used is "application/x-javascript" (the "x-" prefix indicates that it is an experimental, nonstandard type). RFC 4329 standardizes the "text/javascript" type because it is in common use. However, because JavaScript programs are not really text documents, it marks this type as obsolete and recommends "application/javascript" (without the "x-") instead. At the time of this writing, "application/javascript" is not well supported, however. Once it has become well supported, the most appropriate <script> and <meta> tags will be:

 <script type="application/javascript"></script> <meta http-equiv="Content-Script-Type" content="application/javascript"> 

When the <script> tag was first introduced, it was a nonstandard extension to HTML and did not support the type attribute. Instead, the scripting language was defined with the language attribute. This attribute simply specifies the common name of the scripting language. If you are writing JavaScript code, use the language attribute as follows:

 <script language="JavaScript">     // JavaScript code goes here </script> 

And if you are writing a script in VBScript, use the attribute like this:

 <script language="VBScript">     ' VBScript code goes here (' is a comment character like // in JavaScript) </script> 

The HTML 4 specification standardized the <script> tag, but it deprecated the language attribute because there is no standard set of names for scripting languages. Sometimes you'll see <script> tags that use the type attribute for standards compliance and the language attribute for backward compatibility with older browsers:

 <script type="text/javascript" language="JavaScript"></script> 

The language attribute is sometimes used to specify the version of JavaScript in which a script is written, with tags like these:

 <script language="JavaScript1.2"></script> <script language="JavaScript1.5"></script> 

In theory, web browsers ignore scripts written in versions of JavaScript that they do not support. That is, an old browser that does not support JavaScript 1.5 will not attempt to run a script that has a language attribute of "JavaScript1.5". Older web browsers respect this version number, but because the core JavaScript language has remained stable for a number of years, many newer browsers ignore any version number specified with the language attribute.

13.2.4. The defer Attribute

As mentioned earlier, a script may call the document.write( ) method to dynamically add content to a document. Because of this, when the HTML parser encounters a script, it must normally stop parsing the document and wait for the script to execute. The HTML 4 standard defines a defer attribute of the <script> tag to address this problem.

If you write a script that does not produce any document outputfor example, a script that defines a function but never calls document.write( )you may use the defer attribute in the <script> tag as a hint to the browser that it is safe to continue parsing the HTML document and defer execution of the script until it encounters a script that cannot be deferred. Deferring a script is particularly useful when it is loaded from an external file; if it is not deferred, the browser must wait until the script has loaded before it can resume parsing the containing document. Deferring may result in improved performance in browsers that take advantage of the defer attribute. In HTML the defer attribute does not have a value; it simply must be present in the tag:

 <script defer>     // Any JavaScript code that does not call document.write( ) </script> 

In XHTML, however, a value is required:

 <script defer  ="defer"></script> 

At the time of this writing, Internet Explorer is the only browser that uses the defer attribute. It does this when it is combined with the src attribute. It does not implement it quite correctly, however, because deferred scripts are always deferred until the end of the document, instead of simply being deferred until the next nondeferred script is encountered. This means that deferred scripts in IE are executed out of order and must not define any functions or set any variables that are required by the nondeferred scripts that follow.

13.2.5. The <noscript> Tag

HTML defines the <noscript> element to hold content that should be rendered only if JavaScript has been disabled in the browser. Ideally, you should to craft your web pages so that JavaScript serves as an enhancement only, and the pages "degrade gracefully" and still function without JavaScript. When this is not possible, however, you can use <noscript> to notify the users that JavaScript is required and possibly to provide a link to alternative content.

13.2.6. The </script> Tag

You may at some point find yourself writing a script that uses the document.write( ) method or innerHTML property to output some other script (typically into another window or frame). If you do this, you'll need to output a </script> tag to terminate the script you are creating. You must be careful, though: the HTML parser makes no attempt to understand your JavaScript code, and if it sees the string "</script>" in your code, even if it appears within quotes, it assumes that it has found the closing tag of the currently running script. To avoid this problem, simply break up the tag into pieces and write it out using an expression such as "</" + "script>":

 <script> f1.document.write("<script>"); f1.document.write("document.write('<h2>This is the quoted script</h2>')"); f1.document.write("</" + "script>"); </script> 

Alternatively, you can escape the / in </script> with a backslash:

 f1.document.write("<\/script>"); 

In XHTML, scripts are enclosed in CDATA sections, and this problem with closing </script> tags does not occur.

13.2.7. Hiding Scripts from Old Browsers

When JavaScript was new, some browsers did not recognize the <script> tag and would therefore (correctly) render the content of this tag as text. The user visiting the web page would see JavaScript code formatted into big meaningless paragraphs and presented as web page content! The workaround to this problem was a simple hack that used HTML comments inside the script tag. JavaScript programmers habitually wrote their scripts like this:

 <script language="JavaScript"> <!-- Begin HTML comment that hides the script         // JavaScript statements go here         //              .         //              . // End HTML comment that hides the script --> </script> 

Or, more compactly, like this:

 <script><!-- // script body goes here //--></script> 

In order to make this work, client-side JavaScript tweaks the core JavaScript language slightly so that the character sequence <!-- at the beginning of a script behaves just like //: it introduces a single-line comment.

The browsers that required this commenting hack are long gone, but you will probably still encounter the hack in existing web pages.

13.2.8. Nonstandard Script Attributes

Microsoft has defined two completely nonstandard attributes for the <script> tag that work only in Internet Explorer. The event and for attributes allow you to define event handlers using the <script> tag. The event attribute specifies the name of the event to be handled, and the for attribute specifies the name or ID of the element for which the event is to be handled. The content of the script is executed when the specified event occurs on the specified element.

These attributes work only in IE, and their functionality can easily be achieved in other ways. You should never use them; they are mentioned here only so that you will know what they are if you encounter them in existing web pages.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net