Skip to content
ImagineWorld

The Web Browser

node_idnode-book_the-secret-life-of-programs_chapter-12-the-web-browser
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleThe Web Browser
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/slp-fig-12-01-robot-holding-a-sign-with-letters-y.png, assets/slp-fig-12-02-diagram-showing-browser-and-server-connected-by.png, assets/slp-fig-12-03-diagram-showing-url-anatomy-httpswwwnostarchcomcataloggeneralcomputing-with-labels.png, assets/slp-fig-12-04-browser-window-titled-my-first-web-page.png, assets/slp-fig-12-05-nested-html-elements-diagram-showing-html-headtitle.png, assets/slp-fig-12-06-html-document-tree-structure-showing-nodes-html.png, assets/slp-fig-12-07-html-document-tree-diagram-showing-nodes-html.png, assets/slp-fig-12-08-html-element-data-structure-diagram-showing-tag.png, assets/slp-fig-12-09-diagram-showing-browser-containing-dom-javascript-program.png, assets/slp-fig-12-10-browser-block-diagram-showing-components-like-communications.png
local graph

You probably don’t think of it this way, but the web browser you use every day is a virtual machine—an abstract computer with an incredibly complicated instruction set implemented entirely in software. In other words, it’s one of those interpreters you learned about in the last chapter.

In this chapter, you’ll learn about some of the functionality of this virtual machine. You’ll learn about the input language and how it’s interpreted by the browser. Browsers are extremely complicated beasties, however, so I can’t cover every feature.

One thing that makes browsers interesting to learn about is that, on one hand, they’re big, complex applications, and on the other, they’re software-implemented computers that you can program. Browsers have a developer console, which you can use while playing with the examples from this chapter. This allows you to get a real-time view of how the browser operates.

[!visual-conversion] robot holding a sign with letters ‘Y’, ‘GE’, ‘N’ Cropped from the scan (PDF page 277, printed p. 237): robot holding a sign with letters ‘Y’, ‘GE’, ‘N’

Understanding the web browser also teaches us something about system design, which is arguably more important than programming (Chapter 15 covers system design in more detail). The popularity of the web has turned the browser into a magnet for new features. Many of these features have extended browser functionality in a compatible manner by adding to the original instruction set. Other features have duplicated existing functionality in incompatible ways, the result being that browsers now support multiple instruction sets, and the complete set of features is not available in any of them. It should become clear in this chapter that I’m not thrilled by the latter category of features—those that are merely different instead of adding value.

For starters, having multiple ways to do things means you as a programmer have a lot more to learn, which isn’t a great use of your time for features that don’t add value. And you need to expend energy choosing which way to do your code. Adding multiple approaches also increases the complexity of programs. Industry statistics show a direct relationship between the amount of code in a program and the number of bugs. Browsers crash often. And, as Chapter 13 covers in more detail, more complex code is more likely to contain security problems.

Incompatible ways of doing things makes programmers more prone to errors. It’s like an American driving a car in New Zealand: some of the controls are in different places because New Zealanders drive on the left-hand side of the road. People from countries where you drive on the right are easy to spot, as they turn on their windshield wipers when making a turn. You don’t want to program in an environment that facilitates these sorts of avoidable errors.

In my opinion, the fact that many of the web standards have become living documents is a clear sign of trouble. If you’re not familiar with that term, I’m referring to online documents that are constantly being updated. Standards exist to provide stability and interoperability. Living documents don’t; at best, they capture a moment in time. It’s difficult to program to constantly changing specifications. In this context, living documents make life easier for a few document creators (because those documents and the software that they reference never have to be “done”) and more difficult for a much larger number of consumers.

Had this book been written 15 years earlier, this chapter would have started with an introduction to HTML, the HyperText Markup Language. But, as I’ve already implied, the browser has a lot in common with the Great Pacific Garbage Patch: it keeps getting bigger by attracting features that stick to it. Among these are multiple markup languages, so we’ll begin with an overview of them.

Markup is a system for annotating or adding marks to text in a way that can be distinguished from that text—like homework that a teacher has written snarky comments in red pencil on.

Markup languages are not new; they existed long before computers. They were developed as a side effect of the printing press so that authors and editors could describe what they wanted to the “pressmen” who set the type. This useful notion was carried forward when computers automated typesetting. Today’s markup languages are just the latest incarnations of an old idea.

There are a large number of markup languages. For example, I originally wrote this book in a markup language for typesetting called troff. The source for this paragraph is shown in Listing 9-1.


.PP

There are a large number of markup languages.

For example, I originally wrote this book in a markup language for typesetting, called \fCtroff\fP.

The source for this paragraph is shown in Listing 9-1.


Listing 9-1: troff for the preceding paragraph

As you can see, most of it is just the text, but there are three elements of markup. The .PP tells troff to start a paragraph. The \fC tells troff to push the current font onto a stack and replace it with font C, for Courier. The \fP tells troff to pop the font stack (see “Stacks” on page 122), which restores the previous font.

Web pages are regular text files, just like the troff example. You don’t need a fancy program to create them; you can do it in any text editor. As a matter of fact, fancy web page creation programs produce bloated results that you can easily beat by handcrafting them yourself.

How do you mark up a regular text file when the only tool available is more text? By giving superpowers to some characters, the way Superman has superpowers even though he’s also a mild-mannered reporter. For example, troff gives superpowers to any line that begins with a . or ' and to anything that begins with a \.

IBM rolled its own markup language, called GML (short for Generalized Markup Language, though it’s really named for its developers, Goldfarb, Mosher, and Lorie), which the company used for its ISIL publishing tool. This work was expanded into the Standard Generalized Markup Language (SGML), which was adopted by the International Standards Organization in the 1980s. SGML was so “generalized” that it’s not clear that anybody was ever able to produce a complete working implementation of the standard.

eXtensible Markup Language (XML) is a more practical subset of SGML. Support for it was a later addition to browsers.

HTML and XML both have their roots in SGML. They borrow some of the same syntax but don’t conform to the standard.

XHTML is a modified form of HTML that conforms to the XML rules.

The first web browser (called WorldWideWeb), invented by English engineer and computer scientist Sir Tim Berners-Lee in 1990, was pretty

straightforward in how it worked, as shown in Figure 9-1. The browser used a Uniform Resource Locator (URL) to request a document from a server using the HTTP protocol discussed in “The World Wide Web” on page 159. The server sent the document to the browser, which would display it. The document used to be written in HTML, but now it can be written in a variety of languages.

[!visual-conversion] Diagram showing Browser and Server connected by arrows labeled URL … Cropped from the scan (PDF page 280, printed p. 240): Diagram showing Browser and Server connected by arrows labeled URL and Document.

Figure 9-1: Web browser interaction with web server

URLs are text strings that have some structure. Right now we just care about the three parts of that structure shown in Figure 9-2.

[!visual-conversion] Diagram showing URL anatomy: https://www.nostarch.com/catalog/general-computing with labels Scheme, Host, Path. Cropped from the scan (PDF page 280, printed p. 240): Diagram showing URL anatomy: https://www.nostarch.com/catalog/general-computing with labels Scheme, Host, Path.

Figure 9-2: Anatomy of a URL

The scheme indicates the communication mechanism—for example, https selects HyperText Transfer Protocol (Secure). The server that we want to communicate with is the host. It can be a numeric internet address (see “IP Addresses” on page 159) but is most commonly specified as a domain name (see “Domain Name System” on page 159). The location of the document to be retrieved is the path, which looks just like a filesystem path.

One of the schemes is file. When it’s used, the host/path portion of the URL is a local filename—the name of a file on the same system on which the browser is running. In other words, the file scheme points to a file on your computer.

There are an ever-growing number of schemes, such as bitcoin for cryptocurrencies and tv for television broadcasts. These are similar, and in many cases identical, to the protocols that we saw back in “The World Wide Web.”

As mentioned, the first web pages were documents written in HTML. HTML utilized hypertext—text that links to something else, such as other web pages. Sci-fi buffs can think of it like combining hyperspace with text: you hit a link and, zap, you’re someplace else. Hypertext has been around for quite some time, but the web was its compelling application.

Take a look at the simple HTML document in Listing 9-2.

<html>
<head>
<title>
My First Web Page
</title>
</head>
<body>
This is my first web page.
<b>
<big>
Cool!
</big>
</b>
</body>
</html>

Listing 9-2: My First Web Page

Enter the HTML shown in Listing 9-2 into a file and open it in your browser. You should see something like Figure 9-3.

[!visual-conversion] Browser window titled ‘My First Web Page - Mozilla Firefox’ … Cropped from the scan (PDF page 281, printed p. 241): Browser window titled ‘My First Web Page - Mozilla Firefox’ showing URL ‘file:///home/jon/mywebpage.html’ and rendered text: ‘This is my first web page. Cool!’

Figure 9-3: Browser display of My First Web Page

You can see that the display in Figure 9-3 doesn’t look much like the text in Listing 9-2. That’s because the less-than sign (<) is a character with superpowers. In this case, it begins an element of markup. You might notice that elements come in pairs; for each start <tag> there is a matching end </tag>.

The tag determines how the browser interprets the markup element. Tags are essentially virtual machine instructions. For example, <title> puts its contents—what’s between the start and end tags—into the browser title bar. The <b> and <big> elements make the word “Cool!” bold and big, and it’s part of the <body> of the web page.

Because the < has superpowers, you may wonder how to use that character without the superpowers—for example, if you wanted to display This is my first web page with a <. HTML includes its own form of kryptonite called an entity reference, which is an alternate form of a character. In this case, the sequence &lt; represents the < character without triggering its superpowers. (Of course, now there’s a new superpowered character &, which can itself be represented using the &amp; sequence.) Using an entity reference, you could type This is my first web page with a &lt; and it would look correct.

HTML elements aren’t quite as simple. There are a number of random exceptions where end tags are not required, and there’s a <tag/> form for

elements with no content. XHTML eliminates these exceptions. The only complication that we care about here is attributes, which are optional sets of name/value pairs, as shown in Listing 9-3.

<tag name1="value1" name2="value2" ...>
element content
</tag>

Listing 9-3: HTML elements with attributes

Some attribute names have predefined behaviors; you can include arbitrary attributes for any that aren’t predefined. Attribute values are treated identically, with the exception of class, whose value is treated as a space-separated list of values.

Web browsers process documents according to the Document Object Model (DOM). You can think of a web page as a series of elements that enclose other elements as illustrated by the indentation in the Listing 9-2 HTML. Figure 9-4, which looks sort of like an aerial cutaway view of a twisted matryoshka (Russian nesting) doll, shows what this structure looks like for the code in Listing 9-2.

[!visual-conversion] Nested HTML elements diagram showing html, head/title, body, and b … Cropped from the scan (PDF page 282, printed p. 242): Nested HTML elements diagram showing html, head/title, body, and b tags with text content.

Figure 9-4: Nested elements in an HTML document

Let’s grab that picture by the edge of the HTML and tilt it so that all of the innards hang out the bottom, as shown in Figure 9-5.

Look familiar? It’s our old friend, the directed acyclic graph, or DAG (from “Stacks” on page 122), and a tree structure too (see “Hierarchical Data Structures” on page 199). Not only that, but the HTML can be processed using techniques from Chapter 8 and the result is a parse tree (see “Parse Trees” on page 228).

[!visual-conversion] HTML document tree structure showing nodes: html, head, body, title, … Cropped from the scan (PDF page 283, printed p. 243): HTML document tree structure showing nodes: html, head, body, title, b, big, and their content.

Figure 9-5: HTML document as a tree structure

Tree structures like the DOM are so common that an entire lexicon has developed around them. The examples in Table 9-1 are taken from Figure 9-5.

Term Definition Example
Node An element in the tree html, head, body
Interior node An element in the tree that has arrows entering and leaving title
Terminal node An element in the tree that has no arrows leaving it Cool!
Root The top of the tree html
Parent A node whose arrow points directly to another node html is the parent of head and body
Child A node directly pointed to by another node head and body are children of html
Descendant A node directly or indirectly pointed to by another node title is a descendant of html
Ancestor A node that directly or indirectly points to a node body is an ancestor of big
Sibling A node with a common parent head is a sibling of body

Nodes in a tree are ordered. For example, head is the first child of html, and body is the second and also last child of html.

What does a browser do with a document tree? Although it’s possible that someone could build a piece of computing hardware with instructions corresponding to the HTML elements, nobody has done so yet. That rules out compiling the DOM parse tree into machine language. The other choice is to interpret it using depth-first traversal, as shown in Figure 9-6.

Figure 9-6: HTML document traversal order

As you can see, the browser starts at the root, descends to the first child, then to its first child, and so on until it hits a terminal node. It then goes up to the closest ancestor that has another child and does the same thing from there, and so on until every node in the tree is visited. Note that the ordering follows the way in which the HTML is written. Depth-first traversal is yet another application of stacks.

An original idea behind HTML was that authors wrote web pages and browsers figured out how to display them. This made sense because there was no way for the author to know things like the size of a browser’s window, the screen resolution, or the number of available colors and fonts.

Once the web became popular, the marketing types got their hands on it. Glitz became important. All sorts of stuff got added (mostly via the creation of a new CSS specification) to allow authors to finely control how their pages are displayed. Of course, this is exactly the opposite of the original intent. The result is messy.

HTML web pages originally included styling information. For example, the font element that selected a text font had a size attribute that controlled

[!visual-conversion] HTML document tree diagram showing nodes: html, head, body, title, … Cropped from the scan (PDF page 284, printed p. 244): HTML document tree diagram showing nodes: html, head, body, title, b, big with text content.

the size. This approach didn’t work as well when pages were displayed on a diverse set of devices from desktops to cell phones. Cascading Style Sheets (CSS) separates the styling from the HTML so that the HTML can be written once and have different styles applied depending on the target device.

Figure 9-7 shows a data structure that could be used to represent an HTML element in memory.

[!visual-conversion] HTML element data structure diagram showing tag, attributes, and child … Cropped from the scan (PDF page 285, printed p. 245): HTML element data structure diagram showing tag, attributes, and child nodes with linked lists.

Figure 9-7: HTML element data structure

This diagram looks really complicated, but it simply glues together a few things you’ve already learned about. There’s a compound data type (see “Compound Data Types” on page 189) for elements and another for attributes. The attributes are organized as a singly linked list (see “Singly Linked Lists” on page 191). Elements are arranged in a tree (see “Hierarchical Data Structures” on page 199). Because there are an arbitrary number of children whose ordering matters, they’re organized using a doubly linked list (see “Doubly Linked Lists” on page 198).

This organization matters because CSS uses a variation of regular expressions (see “Regular Expressions” on page 224) called selectors to locate elements in the DOM, similar to how yacc matches tokens on a stack. CSS then allows attributes to be associated with the selected elements. This enables a web page designer, for example, to change the text size depending on the target device or to collapse a side menu into a drop-down menu for devices with smaller screens.

CSS muddies up the terminology. It defines a large number of properties—things like color, font size, and so on. Once these properties are associated with a DOM element, they’re called attributes.

Table 9-2 shows some of the CSS selectors. Originally there were only a few, but new ones are being added at an alarming rate.

Table 9-2: CSS Selectors

Pattern Meaning
* Matches any element
E Matches any element of type E (that is, `...`)
F Matches any element of type F (that is, `...`)
E F Matches any element F that is a descendant of an E element
E > F Matches any element F that is a child of an E element
E + F Matches any element F with an immediate sibling element E
E - F Matches any element F preceded by any sibling element E
E[name] Matches any element E that has attribute name
E[name=value] Matches any element E that has attribute name with value
E[name~="value"] Matches any E element whose name attribute is a space-separated list of words, one of which matches value
E#id Matches any E element that has an ID attribute with a value of id
E.class Matches any E element that has a class attribute with a value of class
E:first-child Matches element E if it is the first child of its parent
E:last-child Matches element E if it is the last child of its parent
E:nth-child(n) Matches element E if it is the nth child of its parent
E:empty Matches element E if it has no children
E:link Matches element E if it is a hyperlink anchor such as ``
E:visited Matches element E if it is a hyperlink anchor such as `` that has been visited
E:hover Matches element E when the mouse hovers over it
E:active Matches element E on which the mouse is down
E:focus Matches element E if it has the input focus, meaning that it’s listening to the keyboard

HTML includes a <link> element that can be used to associate a separate file containing CSS with a web page. That’s the preferred usage because it conforms to the principle of keeping the content separate from the styling. But that’s overkill for what we’re doing here. HTML also includes a <style> element that allows CSS to be embedded directly in HTML documents. That’s what we’ll use for our examples.

Let’s modify our web page from Listing 9-1 to include some simple styling, which is shown in bold in Listing 9-4.

<html>
<head>
<title>
My First Web Page
</title>
<style>
body {
color: blue;
}
big {
color: yellow;
font-size: 200%;
}
</style>
</head>
<body>
This is my first web page.
<b>
<big>
Cool!
</big>
</b>
</body>
</html>

Listing 9-4: Web page with embedded CSS

You can see that there are two selectors in Listing 9-4: body and big. Each selector is followed by a list of property names and values; a colon separates each name from its value, there is a semicolon after the value, and the list of names and values for each selector is enclosed in curly brackets. First, we set the color of all text in the document body to blue. Next, we set the color of the text inside the <big> element to yellow, and we set the font-size to 200% of normal. Give it a try!

CSS was an afterthought; nobody had it in mind when developing HTML. There are some quirks as a result. HTML has all sorts of elements with defined meanings. For example, there is a <b> element that makes text bold and a <i> element for italics. But the CSS snippet in Listing 9-5 changes their meanings to be the opposite.

b {
font-style: italic;
font-weight: normal;
}
i {
font-style: normal;
font-weight: bold;
}

Listing 9-5: Swapping bold and italic using CSS

For all intents and purposes, CSS eliminates the distinction between many HTML elements. You can think of HTML elements as having a default set of styles, but once those styles are changed via CSS, the element name may no longer have any relation to to its original purpose.

CSS originally just provided a more flexible mechanism for attaching attributes to elements, but then it started adding new attributes. These new attributes were not retrofitted into HTML. As a result, some attributes

can be specified in both HTML and CSS, and others only in CSS. There’s a bit of an attitude among the programming community that the old way should no longer be used, but that ignores the issues of maintaining existing code.

XML looks a lot like HTML. However, like SGML it requires well-formed elements. This means that each <tag> must have a matching </tag>. Implicit end tags are not permitted. The big distinction between HTML and XML is that HTML was created for a specific application: web pages. XML is a general-purpose markup language that can be used for many different applications.

Most XML tags don’t have preassigned meanings. You can assign any meaning to them that you want. XML provides structure you can use to create your own application-specific markup languages. For example, suppose you want to keep track of vegetables in your garden. You could create a Vegetable Markup Language (VML) that looks like Listing 9-6.

<xml>
<garden>
<vegetable>
<name>tomato</name>
<variety>Cherokee Purple</variety>
<days-until-maturity>80</days-until-maturity>
</vegetable>
<vegetable>
<name>rutabaga</name>
<variety>American Purple Top</variety>
<days-until-maturity>90</days-until-maturity>
</vegetable>
<vegetable>
<name>rutabaga</name>
<variety>Helenor</variety>
<days-until-maturity>100</days-until-maturity>
</vegetable>
<vegetable>
<name>rutabaga</name>
<variety>White Ball</variety>
<days-until-maturity>75</days-until-maturity>
</vegetable>
<vegetable>
<name>rutabaga</name>
<variety>Purple Top White Globe</variety>
<days-until-maturity>45</days-until-maturity>
</vegetable>
</garden>
</xml>

Listing 9-6: XML-based markup language example

Conflicts can arise from allowing people to create their own markup languages, however. For example, suppose that in addition to VML, someone else creates a Recipe Markup Language (RML) that also includes a <name> element, as in Listing 9-7.

<xml>
<garden>
<vegetable>
<name>tomato</name>
<variety>Cherokee Purple</variety>
<days-until-maturity>80</days-until-maturity>
<name>Purple Tomato Salad</name>
</vegetable>
</garden>
</xml>

Listing 9-7: XML-based markup language example with name conflict

There is no way to tell whether the <name> elements are vegetable names or recipe names. We need a mechanism to allow us to combine VML and RML without confusing the <name> elements. This mechanism is an element tag prefix known as a namespace.

As you’d expect from something browser related, there are multiple ways to specify namespaces, but I cover only one of them here. Each namespace is associated with a URL, although there’s no requirement that it be a valid URL; it just has to be distinct from the others. The xmlns attribute on the <xml> element associates a namespace prefix with a URL. Listing 9-8 shows our combined garden and recipe markups with distinguishing namespaces.

<xml xmlns:vml="http://www.garden.org" xmlns:rml="http://www.recipe.org">
<vml:garden>
<vml:vegetable>
<vml:name>tomato</vml:name>
<vml:variety>Cherokee Purple</vml:variety>
<vml:days-until-maturity>80</vml:days-until-maturity>
<rml:name>Purple Tomato Salad</rml:name>
</vml:vegetable>
</vml:garden>
</xml>

Listing 9-8: XML-based markup language example with namespaces

You can see that the elements from both fictitious markup languages are combined and that they are distinguished by prefix. The namespace prefix is arbitrary and left up to whatever is combining the different markup languages together. There’s no requirement that rml be the prefix for the Recipe Markup Language; we could choose recipe if we needed to combine this code with another RML, such as Ridiculous Markup Language.

Plenty of tools are available to help you write applications that understand custom markup languages such as the ones just described. There are also libraries for many programming languages that create and operate on parse trees from XML documents.

One tool is a Document Type Definition (DTD). You can think of this as meta-markup. A DTD is an XML-looking document (there are no ending tags for some reason) that defines the legal elements in a markup language. XML includes a mechanism that allows an XML document to reference a DTD. You could, for example, make a DTD that says that one or more <vegetable> elements are allowed in a <garden> element and that a <vegetable> can contain only <name>, <variety>, and <days-until-maturity> elements. XML parsers can validate the XML against the DTD. Although this is useful, it doesn’t do the most important part. For example, although a DTD can ensure that a required <variety> exists, it can’t test for a valid variety.

The XML Path Language (XPath) provides selectors for XML documents by, as you might guess, creating yet another incompatible syntax; it has essentially the same functionality of CSS selectors but in a completely different syntax that you may need to learn. XPath isn’t very useful by itself but is an important component of Xtensible Stylesheet Language Transformations (XSLT).

XSLT is yet another XML-based language. When combined with XPath, it allows you to write a piece of XML that transforms an XML document into other forms by searching and modifying the parse tree. Listing 9-9 shows a simple example where an XPath expression is used to match any vegetable in the garden and then output the name and variety of each, separated by a space.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/garden/vegetable">
<xsl:value-of select="variety"/>
<xsl:text> </xsl:text>
<xsl:value-of select="name"/>
</xsl:template>
</xsl:stylesheet>

Listing 9-9: Call any vegetable using XSLT and XPath

Applying the XSLT in Listing 9-9 to the XML in Listing 9-6 produces the results in Listing 9-10.

Cherokee Purple tomato
American Purple Top rutabaga
Helenor rutabaga
White Ball rutabaga
Purple Top White Globe rutabaga

Listing 9-10: Call any vegetable results

Another example is shown in Listing 9-11, which selects only vegetables when the value of the name is rutabaga.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/garden/vegetable[name/text()='rutabaga']">
<xsl:value-of select="name"/>
<xsl:text> </xsl:text>
</xsl:template>
</xsl:stylesheet>

<xsl:template match=“text()”/> </xsl:stylesheet>

Listing 9-11: Call it by name

Applying the XSLT from Listing 9-11 to the XML in Listing 9-6 produces what you see in Listing 9-12.

rutabaga rutabaga rutabaga rutabaga

Listing 9-12: Call it by name results

XSLT is especially useful for transforming markup containing arbitrary data into HTML for display in a browser.

Our example web page is static—that is, all it does is display some formatted text. Going back to Figure 9-1, the only way to change what’s displayed is to send another URL to a web server to get a new document. Not only is this a slow process, but it also wastes resources. If you entered a phone number into a form, the data would have to be sent to a server to determine whether it contained all numbers, and the server would have to send back a page with an error message if it didn’t.

In 1993, Mark Andreessen created the graphical Mosaic web browser, which fueled the consumer internet boom. He went on to found Netscape, which released the Netscape Navigator browser in 1994. Realizing the need for more interactive web pages, Netscape introduced the JavaScript programming language in 1995. JavaScript has since been standardized by the Ecma International standards organization, formerly the European Computer Manufacturers Association, as ECMA-262. It’s also known as ECMAScript, which sounds like a skin condition and has since been known to make browsers flaky. JavaScript borrowed from both the C programming language and from Java, which itself borrowed from C.

JavaScript allows web pages to contain actual programs that run on your computer instead of on the server. These programs can modify the DOM and can communicate directly with a web server, as shown in Figure 9-8.

[!visual-conversion] Diagram showing Browser containing DOM, JavaScript program, and Server with … Cropped from the scan (PDF page 291, printed p. 251): Diagram showing Browser containing DOM, JavaScript program, and Server with bidirectional arrows between them.

Figure 9-8: Web browser interaction with JavaScript and web server

The interaction between the JavaScript program and the server is not the same as the browser/server communication we saw in Figure 9-1. Instead, it takes place via Asynchronous JavaScript and XML (AJAX). Let’s break that down. Asynchronous is related to what we saw with ripple counters in “Counters” on page 77; in this instance, it means the browser has no control over when (and if) a server responds. The JavaScript part just means it’s under the control of a JavaScript program. I’m not going to explain the and. Finally, the data from the server to the JavaScript program was initially encoded using XML, not HTML.

You can include JavaScript in an HTML document by enclosing it in <script> elements. Let’s add some to what we had in Listing 9-4, again showing the changes in bold, in Listing 9-13.

<html>
<head>
<title>
My First Web Page
</title>
<style>
body {
color: blue;
}
big {
color: yellow;
font-size: 200%;
}
</style>
<script>
window.onload = function() {
var big = document.getElementsByTagName('big');
big[0].style.background = "green";
}
</script>
</head>
<body>
This is my first web page.
<b>
<big>
Cool!
</big>
</b>
</body>
</html>

Listing 9-13: Web page with embedded JavaScript

Let’s see what this does without going into all the nitpicky details. Part of the browser definition is that there is a window.onload variable that can be set to a function to execute when the initial page has finished loading. Another part of the definition says that there is a document.getElementsByTagName function that returns an array of all matching elements in the DOM. Here it returns the one element. Finally, it allows us to change various element properties. In this case, we set the background color to green.

There are a large number of defined functions for DOM manipulation. They allow us to do more than just change CSS styles from a program. There are also functions that allow you to rearrange the DOM tree, including the ability to add and delete elements.

Using the browser DOM functions from the previous section has two problems. First, the DOM functions don’t have exactly the same behavior on different browsers. Second, they’re pretty cumbersome to use—not exactly a user-friendly interface.

Enter jQuery, a library introduced by American software engineer John Resig in 2006. It solved both of the problems just mentioned. It smoothed over the incompatibilities between browsers so that the programmers using it didn’t have to. And it supplied a DOM manipulation interface that was much easier to use.

The jQuery library combines selectors with actions. The code in Listing 9-14 does exactly the same thing as the code in Listing 9-13 but in a more programmer-friendly way.

<html>
<head>
<title>
My First Web Page
</title>
<style>
body {
color: blue;
}
big {
color: yellow;
font-size: 200%;
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
<script>
$(function() {
$('big').css('background', 'green');
});
</script>
</head>
<body>
This is my first web page.
<b>
<big>
Cool!
</big>
</b>
</body>
</html>

Listing 9-14: Web page with embedded JavaScript and jQuery

The first <script> element imports the jQuery library; the second contains our code. The “document ready” function that the browser calls when the page is loaded contains a single jQuery statement. The first part of it, $('big'), is a selector. It’s similar to the CSS selectors we saw in Table 9-2. The remainder of the statement, .css('background', 'green'), is an action to perform on the selected elements. In this case, the css function modifies the background property, setting it to green.

Let’s add the piece of jQuery in Listing 9-15 to the document ready function to add some interactivity.

$('big').click(function() {
$('big').before('<i>Very</i>');
$('big').css('font-size', '500%');
});

Listing 9-15: jQuery event handler

This simple piece of code attaches an event handler to the <big> element that is executed when the mouse clicks it. This handler does two things: it inserts a new <i> element before the <big> element, and it increases the <big> font size.

As you can see in this example, jQuery makes it easy to manipulate the DOM using JavaScript. You can open up your browser’s debugging console and watch these changes occur when you click.

jQuery blazed a path, and a very popular one at that; the library is very widely used. However, as seems endemic in the web community, some programmers decided to create parallel, incompatible paths. There are now a number of JavaScript libraries that do the same things, only differently.

Scalable Vector Graphics (SVG) is kind of an odd duck in the collection of browser additions. It’s yet another completely different language that allows you to produce nice-looking graphics and text in a manner that is completely incompatible with everything else.

John Warnock and Chuck Geschke founded Adobe Systems in 1982 and developed the PostScript language. Warnock had been working on more complicated versions of the ideas in PostScript for years, and the development of PostScript was similar to the way that the overly complex SGML was simplified to HTML. The duo caught a lucky break when Steve Jobs requested that they use PostScript to drive laser printers. The PostScript-based Apple LaserWriter was a major factor in the formation of the desktop publishing industry and was responsible for Adobe’s success.

PostScript had some issues with portability—getting the same results everywhere. The Portable Document Format (PDF), based on PostScript, was

created to address these issues. SVG is more or less PDF wedged into browsers. Of course, SVG and PDF aren’t completely compatible because that would make too much sense.

In general, SVG is more automatic than the recently added canvas (covered in the next section). You can tell it to do things, and it will, whereas with a canvas you have to write a program to manipulate it. Add the contents of Listing 9-16 to the body of your web page and give it a spin, because every web page needs a red pulsing circle.

<br>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<circle id="c" r="10" cx="200" cy="200" fill="red"/>
<animate xlink:href="#c" attributeName="r" from="10" to="200" dur="5s" repeatCount="indefinite"/>
</svg>

Listing 9-16: SVG animated circle

As I mentioned at the beginning of this chapter, it seems that in the browser world, there’s no idea that should be implemented only once. HTML5 is the latest incarnation of HTML. Among other things, it adds a big pile of semantic elements, including <header>, <footer>, and <section>, which—if used as intended—would add consistent structure to documents.

HTML5 introduces the canvas, which provides pretty much the same functionality as SVG but in a completely different way. The major difference is that canvases can be manipulated only with a new set of JavaScript functions, unlike SVG, which can use the existing DOM functions. In other words, you would have to write a JavaScript program in order to duplicate Listing 9-16 using a canvas.

HTML5 also adds <audio> and <video>, which provide somewhat standard mechanisms for audio and video.

I touched on AJAX back in “JavaScript” on page 251 and mentioned that asynchronous XML-formatted data is sent from the server to the browser JavaScript program. Well, that’s so four sections ago. The X in AJAX is now a J for JSON. Although the acronym AJAX floats around, the technique is still called AJAX.

JSON stands for JavaScript Object Notation. It’s essentially a human-readable text format for a JavaScript object, which is one of JavaScript’s compound data types. The theory is that data in this format can be exchanged in an interoperable manner, although problems with the specification mean that this exchange is possible only if you adhere to certain unspecified rules such as avoiding certain characters. Programmers also need to work around the fact that JSON doesn’t support all the JavaScript data types.

Listing 9-17 builds a JavaScript object and converts it to JSON format. It then shows the result that was stored in the variable the_quest, shown in bold below.

var argonauts = {};
argonauts.goal = "Golden Fleece";
argonauts.sailors = [];
argonauts.sailors[0] = { name: "Acastus", father: "Pelias" };
argonauts.sailors[1] = { name: "Actor", father: "Hippasus" };
argonauts.sailors[2] = { name: "Admentus", father: "Pheres" };
argonauts.sailors[3] = { name: "Amphiarus", father: "Oicles" };
argonauts.sailors[4] = { name: "Ancaeus", father: "Poseidon" };
var the_quest = JSON.stringify(argonauts);
{
"goal": "Golden Fleece",
"sailors": [
{ "name": "Acastus", "father": "Pelias" },
{ "name": "Actor", "father": "Hippasus" },
{ "name": "Admentus", "father": "Pheres" },
{ "name": "Amphiarus", "father": "Oicles" },
{ "name": "Ancaeus", "father": "Poseidon" }
]
}

Listing 9-17: JSON and the Argonauts

JSON has an advantage over XML when using JavaScript, and not just because converting JavaScript objects into JSON is trivial, as shown in Listing 9-17. The companion JavaScript eval function can execute JSON directly, because it’s data, as if it’s a JavaScript program. JSON is popular because it eliminates the need for extra code to handle data export and import.

Just because it’s easy to use JSON doesn’t mean you can be cavalier about it, however. Blithely importing JSON data using eval can allow an attacker to execute arbitrary code in a browser. More recently, a companion JSON.parse function has been added that safely converts JSON back into a JavaScript object.

In this chapter, you’ve learned the basics of how many of the components comprising a web browser work. Figure 9-9 illustrates the pieces we’ve discussed. Of course, browsers include a lot more functionality that isn’t particularly interesting, such as bookmarks and history.

[!visual-conversion] Browser block diagram showing components like Communications interface, Language parser, … Cropped from the scan (PDF page 297, printed p. 257): Browser block diagram showing components like Communications interface, Language parser, JavaScript interpreter, Document object model data, and User interface engine with their sub-components and connections.

Figure 9-9: Browser block diagram

The diagram may look pretty complicated, but it’s just an assemblage of parts that you’ve already seen. These include language parsers, parse trees, regular expressions, interpreters, networking, input, and output.

It also illustrates a distinction between hardware and software design. Designing hardware is more expensive than designing software. It’s unlikely that a hardware designer would construct a system that used six different incompatible methods to do the same thing before breakfast. But because there isn’t the same up-front cost in software, software designers are often less careful. The result is often a larger, more complex result that might cost less up front but often costs more later because of the number of complicated interoperating parts that must be maintained.

Now that you’ve learned something about the workings of this complex interpreter, in the next chapter we’ll write some programs for it. You’ll see a program written for a browser in JavaScript and the same program written in C. This will illustrate some of the important system-level considerations that are hidden from web programmers but are important for system-level programming.