loading...

JavaScript – Embedding JavaScript in HTML

Client-side JavaScript code is embedded within HTML documents in
four ways:

  • Inline, between a pair of <script> and </script> tags

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

  • In an HTML event handler attribute, such as onclick or onmouseover

  • In a URL that uses the special javascript: protocol.

The subsections that follow explain each of these four
JavaScript embedding techniques. It is worth noting, however, that
HTML event handler attributes and javascript:
URLs are rarely used in modern JavaScript code (they were somewhat
common in the early days of the Web). Inline scripts (those without a
src attribute) are also less common
than they once were. A programming philosophy known as
unobtrusive JavaScript argues that content (HTML)
and behavior (JavaScript code) should as much as possible be kept
separate. According to this programming philosophy, JavaScript is best
embedded in HTML documents using <script> elements with src attributes.

The <script> Element

JavaScript code can appear inline within an HTML file between
<script> and </script> tags:

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

In XHTML, the content of a <script> element 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>

Example 13-2 is an HTML file that
includes a simple JavaScript program. The comments explain what the
program does, but the main point of this example is to demonstrate
how JavaScript code is embedded within an HTML file along with, in
this case, a CSS stylesheet. Notice that this example has a
structure similar to Example 13-1 and uses the
onload event handler in much the
same way as that example did.

Example 13-2. A simple JavaScript digital clock

<!DOCTYPE html>                 <!-- This is an HTML5 file -->
<html>                          <!-- The root element -->
<head>                          <!-- Title, scripts & styles go here -->
<title>Digital Clock</title>
<script>                        // A script of js code
// Define a function to display the current time
function displayTime() {
    var elt = document.getElementById("clock");  // Find element with id="clock"
    var now = new Date();                        // Get current time
    elt.innerHTML = now.toLocaleTimeString();    // Make elt display it
    setTimeout(displayTime, 1000);               // Run again in 1 second
}
window.onload = displayTime;  // Start displaying the time when document loads.
</script>
<style>                         /* A CSS stylesheet for the clock */
#clock {                        /* Style apply to element with id="clock" */
  font: bold 24pt sans;         /* Use a big bold font */
  background: #ddf;             /* On a light bluish-gray background */
  padding: 10px;                /* Surround it with some space */
  border: solid black 2px;      /* And a solid black border */
  border-radius: 10px;          /* Round the corners (where supported) */
}
</style>
</head>
<body>                    <!-- The body is the displayed parts of the doc. -->
<h1>Digital Clock</h1>    <!-- Display a title -->
<span ></span>  <!-- The time gets inserted here -->
</body>
</html>

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="../../scripts/util.js"></script>

A JavaScript file contains pure JavaScript, without <script> tags or any other HTML. By
convention, files of JavaScript code have names that end with
.js.

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. Note that the
closing </script> tag is
required in HTML documents even when the src attribute is specified, and there is
no content between the <script> and </script> tags. In XHTML, you can
use the shortcut <script/>
tag in this case.

When you use the src
attribute, any content between the opening and closing <script> tags is ignored. If
desired, you can use the content of the <script> tag to include
documentation or copyright information for the included code. Note,
however, that HTML5 validators will complain if any text that is not
whitespace or a JavaScript comment appears between <script src=""> and </script>.

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 them—that is, it helps keep
    content and behavior separate.

  • When multiple web pages share the same JavaScript code,
    using the src attribute
    allows you to maintain only a single copy of that code, rather
    than having to edit each HTML file when the code changes.

  • If a file of JavaScript code is shared by more than one
    page, it only needs to be downloaded once, by the first page
    that uses it—subsequent pages can retrieve it from the browser
    cache.

  • 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.

  • The ability to load scripts from other sites allows us to
    take the benefits of caching a step further: Google is promoting
    the use of standard well-known URLs for the most commonly used
    client-side libraries, allowing the browser to cache a single
    copy for shared use by any site across the Web. Linking to
    JavaScript code on Google servers can decrease the start-up time
    for your web pages, since the library is likely to already exist
    in the user’s browser cache, but you must be willing to trust a
    third-party to serve code that is critical to your site. See
    http://code.google.com/apis/ajaxlibs/ for
    more information.

Loading scripts from servers other than the one that served
the document that uses the script has important security
implications. The same-origin security policy described in The Same-Origin Policy 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.

Script Type

JavaScript was the original scripting language for the Web and
<script> elements are, by
default, assumed to contain or to reference JavaScript code. If you
want to use a nonstandard scripting language, such as Microsoft’s
VBScript (which is supported by IE only), you must use the type attribute to specify the script MIME
type:

<script type="text/vbscript">
' VBScript code goes here
</script>

The default value of the type attribute is “text/javascript”. You
can specify this type explicitly if you want, but it is never
necessary.

Older browsers used a language attribute on the <script> tag instead of the type attribute, and you may still
sometimes see web pages that include tags like this:

<script language="javascript">
// JavaScript code here...
</script>

The language attribute is
deprecated and should no longer be used.

When a web browser encounters a <script> element with a type attribute whose value it does not
recognize, it parses the element but does not attempt to display or
execute that content. This means that you can use the <script> element to embed arbitrary
textual data into your document: just use the type attribute to specify a non-executable
type for your data. To retrieve the data, you can use the text property of the
HTML


Element

object that represents the script element (Chapter 15 explains how to obtain these elements). Note,
however, that this data embedding technique only works for inline
scripts. If you specify a src
attribute and an unknown type,
the script will be ignored and nothing will be downloaded from the
URL you specified.

Event Handlers in HTML

JavaScript code in a script is executed once: when the HTML
file that contains it is loaded into the web browser. In order to be
interactive, a JavaScript program must define event
handlers—JavaScript functions that are registered with the web
browser and then invoked by the web browser in response to events
(such as user input). As shown at the start of this chapter,
JavaScript code can register an event handler by assigning a
function to a property (such as onclick or onmouseover) of an Element object that
represents an HTML element in the document. (There are also other
ways to register event handlers—see Chapter 17.)

Event handler properties like onclick mirror HTML attributes with the
same names, and it is also possible to define event handlers by
placing JavaScript code in HTML attributes. For example, to define
an event handler that is invoked when the user toggles a checkbox in
a form, you can specify the handler code as an attribute of the HTML
element that defines the checkbox:

<input type="checkbox" name="options" value="giftwrap"
       onchange="order.options.giftwrap = this.checked;">

What’s of interest here is the onchange attribute. The JavaScript code
that is the value of this attribute will be executed whenever the
user checks or unchecks the checkbox.

Event handler attributes defined in HTML may include any
number of JavaScript statements, separated from each other by
semicolons. These statements become the body of a function, and that
function becomes the value of the corresponding event handler
property. (The details of the conversion of HTML attribute text to a
JavaScript function are covered in Setting Event Handler Attributes.) Typically, however, an HTML event
handler attribute consists of a simple assignment as above or a
simple invocation of a function defined elsewhere. This keeps most
of your actual JavaScript code within scripts and reduces the need
to mingle JavaScript and HTML. In fact, the use of HTML event
handler attributes is considered poor style by many web developers
who prefer to keep content and behavior separate.

JavaScript in URLs

Another way that JavaScript code can be included on the client
side is in a URL following the javascript: protocol specifier. This
special protocol type specifies that the body of the URL is an
arbitrary string of JavaScript code to be run by the JavaScript
interpreter. It is treated as a single line of code, which means
that statements must be separated by semicolons and that /* */ comments must be used in place of
// comments. The “resource”
identified by a javascript: URL
is the return value of the executed code, converted to a string. If
the code has an undefined return
value, the resource has no content.

You can use a javascript:
URL anywhere you’d use a regular URL: the href attribute of an <a> tag, the action attribute of a <form>, for example, or even as an
argument to a method like window.open(). A JavaScript URL in a
hyperlink might look like this:

<a href="javascript:new Date().toLocaleTimeString();">
What time is it?
</a>

Some browsers (such as Firefox) execute the code in the URL
and use the returned string as the content of a new document to
display. Just as when following a link to an http: URL, the browser erases the current
document and displays the new one. The value returned by the code
above does not contain any HTML tags, but if it did, the browser
would have rendered them as it would have rendered the equivalent
conventionally loaded HTML document. Other browsers (such as Chrome
and Safari) do not allow URLs like the one above to overwrite the
containing document—they just ignore the return value of the code.
They do, however, still support URLs like this one:

<a href="javascript:alert(new Date().toLocaleTimeString());">
Check the time without overwriting the document
</a>

When this sort of URL is loaded, the browser executes the
JavaScript code, but because there is no returned value (the
alert() method returns undefined), browsers like Firefox do not
replace the currently displayed document. (In this case, the
javascript: URL serves the same
purpose as an onclick event
handler. The link above would be better expressed as an onclick handler on a <button> element—the <a> element should generally be
reserved for hyperlinks that load new documents.) If you want to
ensure that a javascript: URL
does not overwrite the document, you can use the void operator to force an invocation or
assignment expression to be undefined:

<a href="javascript:void window.open('about:blank');">Open Window</a>

Without the void operator
in this URL, the return value of the Window.open() method call would (in some
browsers) be converted to a string and displayed, and the current
document would be overwritten by a document that contains this
text:

[object Window]

Like HTML event handler attributes, JavaScript URLs are a
holdover from the early days of the Web and are generally avoided in
modern HTML. javascript: URLs do
have a useful role to play outside of HTML
documents. If you need to test a small snippet of JavaScript code,
you can type a javascript: URL
directly into the location bar of your browser. Another legitimate
(and powerful) use of javascript:
URLs is in browser bookmarks, as described below.

Bookmarklets

In a web browser, a “bookmark” is a saved URL. If you
bookmark a javascript: URL, you
are saving a small script, known as a
bookmarklet. A bookmarklet is a
mini-program that can be easily launched from the browser’s menus
or toolbar. The code in a bookmarklet runs as if it were a script
on the page and can query and set document content, presentation,
and behavior. As long as a bookmarklet does not return a value, it
can operate on whatever document is currently displayed without
replacing that document with new content.

Consider the following javascript: URL in an <a> tag. Clicking the link opens a
simple JavaScript expression evaluator that allows you to evaluate
expressions and execute statements in the context of the
page:

<a href='javascript:
  var e = "", r = ""; /* Expression to evaluate and the result */
  do {
      /* Display expression and result and ask for a new expression */
      e = prompt("Expression: " + e + "\n" + r + "\n", e);
      try { r = "Result: " + eval(e); } /* Try to evaluate the expression */
      catch(ex) { r = ex; }             /* Or remember the error instead  */
  } while(e);  /* Continue until no expression entered or Cancel clicked */
  void 0;      /* This prevents the current document from being overwritten */
  '>
JavaScript Evaluator
</a>

Note that even though this JavaScript URL is written across
multiple lines, the HTML parser treats it as a single line, and
single-line // comments will
not work in it. Also, remember that the code is all part of a
single-quoted HTML attribute, so the code may not contain any
single quotes.

A link like this is useful when hardcoded into a page that
you are developing but becomes much more useful when stored as a
bookmark that you can run on any page. Browsers typically allow
you to bookmark the destination of a hyperlink by right-clicking on the link and selecting
something like Bookmark Link or by dragging the link to your
bookmarks toolbar.

Comments are closed.

loading...