the web platform - smlugthe web platform: building a solid stack of html, ... both html markup and...

34

Upload: others

Post on 03-Jun-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 2: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Additional Resources3 Easy Ways to Learn More and Stay Current

©2014 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. 14114

Read more news and analysis about JavaScript, HTML5, CSS3, and other web platform technologies. programming.oreilly.com

Get programming-related news and content delivered weekly to your inbox.oreilly.com/code/newsletter.html

Immerse yourself in learning at the annual O’Reilly Fluent Conference. Join developers, UX/UI designers, project teams, and a wide range of other people who work with web platform technologies to share experiences and expertise— and to learn what you need to know to stay competitive. fluentconf.com

Programming Blog

Programming Newsletter

Fluent Conference

Page 3: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Simon St.Laurent

The Web PlatformBuilding a Solid Stack of HTML,

CSS, and JavaScript

Page 4: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

The Web Platformby Simon St.Laurent

Copyright © 2014 O’Reilly Media, Inc. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA95472.

O’Reilly books may be purchased for educational, business, or sales promotional use.Online editions are also available for most titles (http://my.safaribooksonline.com). Formore information, contact our corporate/institutional sales department: 800-998-9938or [email protected].

Editor: Simon St.Laurent

January 2014: First Edition

Revision History for the First Edition:

2014-01-10: First release

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registeredtrademarks of O’Reilly Media, Inc. The Web Platform: Building a Solid Stack of HTML,CSS, and JavaScript and related trade dress are trademarks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their prod‐ucts are claimed as trademarks. Where those designations appear in this book, andO’Reilly Media, Inc. was aware of a trademark claim, the designations have been printedin caps or initial caps.

While every precaution has been taken in the preparation of this book, the publisherand authors assume no responsibility for errors or omissions, or for damages resultingfrom the use of the information contained herein.

ISBN: 978-1-491-95011-1

[LSI]

Page 5: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

HTML: Moving Beyond the Standard. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

The Power of Markup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

CSS Selectors Have Superpowers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

JavaScript: Not as Expected. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

From JavaScript to Declarative Markup. . . . . . . . . . . . . . . . . . . . . . . . 17

Toward Responsive Web Programming. . . . . . . . . . . . . . . . . . . . . . . . 19

Will JavaScript Take Over the Programming World?. . . . . . . . . . . . . . 21Concentration: The Wrong Story 21Dispersion: A More Likely Story? 24

iii

Page 6: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 7: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Preface

The Web keeps growing, expanding from a content distribution sys‐tem to an application platform connecting people within organiza‐tions and across the world. For the past 15 years, the Web’s core hasproven remarkably stable. Even as developers create more technolo‐gies and techniques, they still mostly use the core stack of HTML plusCSS and JavaScript, with a few extensions mostly provided throughadditional standards.

Can that stack persist? Programmers have longed for alternatives forat least as long as the Web has existed, largely because web develop‐ment doesn’t quite feel like programming. Creating documents, stylingthem, and then adding some program logic is pretty different fromstandard models of creating objects and logic to display something ona screen.

The Web endures, though, largely because of its unique approach.Markup and simple hypertext offered a quick way to build and sharedocuments across a network, but we have layered much more on topof those capabilities. Beyond simplicity—which isn’t especially prev‐alent today—why do web tools work so well?

• Both HTML markup and CSS stylesheets are declarative, makingbrowsers do work without requiring programming logic.

• JavaScript layers well on top of HTML, especially after it learnedthe power of declarative selectors from CSS.

• Separating content, presentation, and logic has made reuse muchsimpler.

v

Page 8: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

• The ubiquity of the Web combined with the competitive natureof browser vendors encourages major investment in renderingengines and JavaScript performance.

• Even though web browsers are written by many different peoplewith different motives, they’ve been able to work well enough to‐gether to extend browser capabilities.

The best part, though, is that those foundations let us do new things.I hope you’ll find that web technologies continue to provide a solidbase on which to build your dream projects!

These pieces were originally written for the O’Reil‐ly Programming blog and then adjusted to betterfit the times and the format. If you’d like to seemore on similar topics, please explore http://programming.oreilly.com.

vi | Preface

Page 9: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

HTML: Moving Beyondthe Standard

You can create your own markup vocabularies without learning XML.You just need to figure out what markup you want to use, and thencreate CSS and JavaScript to tell the browser what to do with it. Cre‐ating your own extensions to the HTML vocabulary lets you describeyour content in the terms that make sense to you and can help youdrastically reduce repetition and confusion.

When HTML first appeared, it offered a coherent if limited vocabularyfor sharing content on the newly created World Wide Web. Today, nowthat HTML has handed off most of its actual work to other specifica‐tions, developers can start to choose their own markup vocabulariesand processing.

When the W3C first formed, it formed around HTML, the core stan‐dard of content on the Web, defining the structure, appearance, andbehavior of content. Over the next few years, however, it became clearthat HTML was doing too much, and the W3C and other groups re‐factored appearance, behavior, and many semantics into separatespecifications:

• Cascading Style Sheets (CSS) took responsibility for presentationand layout.

• JavaScript took responsibility for behavior, aided by the Docu‐ment Object Model (DOM) and a variety of APIs for handlingdevice and multimedia interactions.

1

Page 10: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

• WAI-ARIA took responsibility for accessibility semantics, ensur‐ing that content remained available to a broad audience even ifdevelopers pushed the current boundaries of markup.

It’s not a completely neat separation—some of CSS feels like behavior,and JavaScript can manipulate presentation, for example, but theycertainly took some work off the shoulders of HTML. A few aspectsof HTML, notably media inclusion, are still mostly handled at themarkup level, but most of them aren’t any longer. Forms and linkingare both still defined in HTML itself, but they aren’t difficult to im‐plement separately.

When the WHATWG formed, its focus on web application develop‐ment led it to build a variety of JavaScript tools, which still dominatethe HTML5 work. In many ways, HTML5 has been about adding afew pieces of markup functionality to HTML itself and a tremendouspile of JavaScript APIs to browsers in general.

Browsers still need to do a lot of work to achieve the visions developershave for a unified distributed application platform, but HTML itselfcarries less and less of that burden. The former flagship spec may bewhat comes to mind first when people say “web development,” but thereality is that it has been hollowed out. The heavy lifting happens inthe other specifications.

This means that we can free markup semantics from the demandsoriginally placed on HTML. Markup doesn’t become total anarchy:defined markup syntax, both XML’s stricter version and HTML5’smore forgiving version, is still useful to create a parse tree browserscan decorate with CSS and WAI-ARIA and then manipulate withJavaScript.

HTML itself is still useful—many people and tools know how to readand write it—but there is less and less reason to let the HTML vo‐cabulary be a cage limiting our possibilities. Polyfills emerged as toolsfor bringing older browsers up to date with the latest specifications.Best practices for using them are still emerging, but they’ve become amore common implementation in frameworks like AngularJS, mak‐ing it easy for developers to create markup templates that JavaScriptwill later manipulate. (The Web Components spec simplifies this workand provides structure that works across browsers reliably.)

A stronger case for polyfills, though it was actually meant to argue foradding an element to the standard, comes from the picture element

2 | HTML: Moving Beyond the Standard

Page 11: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

1. I’m not quite ready to join Matthew Butterick in proposing “that the W3C be disban‐ded.” The W3C (and WHATWG) are still doing good work developing the supportinginfrastructure of CSS, WAI-ARIA, and JavaScript APIs. ECMA-262 continues theirwork on JavaScript. The W3C and the browser vendors still have many great things todo to enhance the ways that browsers support markup processing.

saga. The Responsive Images Community Group developed a speci‐fication and implemented it (twice) with polyfills. Those developersweren’t happy when the W3C and WHATWG didn’t seem interested(conversations continue), but from my perspective, they’d alreadydone great work in creating the polyfills. (Loading media has morecomplicated optimization issues than just about anything else brows‐ers do with HTML.)

Shifting the focus away from markup standards is difficult. The WebStandards Project spent a decade or so (and I participated) evangeliz‐ing the need for web standards and disbanded recently in the face ofsuccess. The message that web tools need to be designed by a centralorganization is, for better or worse, deeply ingrained, but it’s time formarkup to fall out of that story.1

HTML’s legacy vocabulary is a great foundation on which developerscan build their own toolsets. The Web will benefit, however, from let‐ting developers solve their information problems in their own ways,rather than trying to stuff too many things into a single vocabulary.Even if centralized markup standards have benefits, let’s evolve themrather than design them.

So where should you start? The Polymer framework is a good place toexperiment, and there’s been a lot of useful conversation at the Exten‐sible Web Community Group. It’s early yet—this approach hasn’t be‐come a standard part of developing a website or app—but it’s time tostart playing.

HTML: Moving Beyond the Standard | 3

Page 12: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 13: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

The Power of Markup

Markup with some brilliantly minimal hypertext options launched theWorld Wide Web. The toolset was approachable, easy to apply to manykinds of information, and laid the foundation for greater things tocome.

In the early days of HTML, it became clear pretty quickly that therewere sane and insane ways to use markup. Some approaches, praised(or sometimes mocked) as “semantic” approaches, made it much sim‐pler to apply Cascading Style Sheets (CSS) to documents and manip‐ulate their structure and content with JavaScript. Even when I was firstwriting about Dynamic HTML, starting from a clean document madeeverything so much easier. (XHTML got traction among at least partof the Web community for just those kinds of reasons.)

When I first got to XML, the markup was still primary and the pro‐cessing an afterthought. Get the markup right—for many differentvalues of right, of course—and the processing will be manageable. Themarkup approach offers some powers that I haven’t found in otherdata models and systems:

• Markup makes declarative approaches feel natural, with a natural“this goes here” system.

• The very term “markup” reminds us that we are indeed markingup documents that may have cohesive value on their own, not justas shredded and codified chunks of data.

• Broken and incomplete documents may yet contain especiallyimportant information.

• Markup leaves the door open for information that didn’t fit insomeone’s prized model, allowing for format evolution rather

5

Page 14: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

than cycles of standardization. The structure of a given documentis almost always easier to change than the programs that processit. (The nodes view emphasizes the priority of programs and alltoo often celebrates the things that make them brittle.)

• Markup makes comprehensible possibilities that can’t be reachedif you lock yourself into nodes from the beginning, like overlap‐ping structures. Programmers indoctrinated into neat structureoften see this as an utter corner case, but those who work withhuman documents know it exists regularly in the wild.

At some point, maybe around the time of the Microsoft “he doesn’tknow what XML is” advertisement, a lot of people arrived in markupwho had no interest in its details.

XML was exciting because it made clear that data interchange waspossible with much simpler tools than its predecessors. Markup wasstill incredibly useful, but as the servant of programmers. XML struc‐tures suddenly had to look like programming structures, becausenothing else could be trusted. They could look a little different, becauseafter all, programmers from different environments had different ex‐pectations, and there were documents to tolerate, but Schemas andWSDL and similarly structured approaches dominated.

More recently, the rise of web applications has brought a similar chal‐lenge to the HTML side of the markup story. Single-page apps oftencarry a tiny bit of markup that launches a JavaScript program, whichthen sets about creating an abstract vision of HTML elements in theDOM. Instead of layering their code on top of markup, the code takesover, and the HTML lingers only as a readable serialization for de‐bugging.

The data hygiene and mental hygiene of programming are not appro‐priate for markup. Programming and markup have connections,much like carpentry and plumbing, but their best practices are verydifferent.

JSON, ASN.1, and similar approaches are much better fits for pro‐gramming, which need only the structure but not the weight of mark‐up. Over time, they (JSON in particular) are eroding XML’s share ofmarkets it was never well suited for anyway.

On the HTML side, I see some return to an appreciation of the valueof markup. Content-first approaches to responsive web design cantake advantage not only of the concrete nature of markup as a foun‐

6 | The Power of Markup

Page 15: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

dation for CSS described in “CSS Selectors Have Superpowers”, but alsoits flexibility—sketching in markup isn’t that hard. Hopefully WebComponents will make it much easier in the near future, letting manymore people enrich the HTML vocabulary with minimal disruption,as described in “HTML: Moving Beyond the Standard”. Even on themore programming-centric side, I see this piece on Isomorphic Java‐Script suggesting a path forward that at least exposes more HTML onthe Web rather than hiding information beyond JavaScript and APIs.

Markup isn’t done yet.

The Power of Markup | 7

Page 16: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 17: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

CSS Selectors Have Superpowers

After years of complaints about Cascading Style Sheets, many stem‐ming from their deliberately declarative nature, it’s time to recognizetheir power. For developers coming from imperative programmingstyles, it might seem hard to lose the ability to specify more complexlogical flow. That loss, though, is discipline leading toward the abilityto create vastly more flexible systems, a first step toward the pattern-matching model common to functional programming.

Way back when I was writing about styling XML in browsers, I didn’teven have to stop to think about how difficult it would be to repurposeCSS selectors for XML documents. Since they weren’t tightly boundto assumptions about HTML beyond the existence of elements andattributes, they just worked.

The tool that most vividly demonstrated the real power of selectors,though, was jQuery. I may have annoyed some people by referring tojQuery as “that framework that lets you use CSS selectors instead ofDOM tree walking” for a while, but Remy Sharp makes clear the powerof that:

The ease in which jQuery could be learnt was the appeal to me. Allthe DOM navigation was done using CSS expression using some in‐sane black box magic that John Resig had come up [with]--saving mylimited brain power, and once I had those DOM nodes, I could dowhat I wanted to them (usually some combinations of showing, hid‐ing, fading and so on).

Over time, as Sharp notes, Web browsers learned from jQuery, build‐ing this basic lesson deeper into their tools and making it work moreefficiently:

9

Page 18: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

In those 7 years, quite a bit has happened. Probably one of the mostimportant steps forward was the introduction of querySelectorAll.Being able to give a native function of a browser a CSS expression,and it doing the work to navigate the DOM is a huge (literally) partof jQuery.

CSS selectors simplified the learning process, but they also simplifiedthe resulting code. Figuring out which node an expression had selectedbecame much, much simpler. Developers could apply the same selec‐tors they were using for code to a stylesheet and quickly resolve anyquestions, and they could readily apply the same stylesheet to multipledocuments if there were further questions.

Why does this work so well, when CSS selectors offer only a few op‐tions and a little logic?

Declarative approaches work extremely well for describing queriesthrough a document. Markup (whether HTML or XML) providesclear hooks for those queries through their element and attributestructures. The queries developers used to do by hunting and peckingthrough the DOM are still available, but most of the time, declarationswill get you there a lot faster, or in identical time.

Browsers can optimize their CSS selector processing, running it inmuch faster native code. A few years ago, I was very surprised to findthat completely switching out stylesheets was faster than making a fewstyle changes through JavaScript directly. Tree walking in JavaScriptmeans a lot of back and forth between the document object and theinterpreted code.

Performance and ease of learning aren’t all you get, though. You alsoget a style of programming that offers vastly more flexibility, becauseselectors are a form of pattern matching. Pattern-matching ap‐proaches don’t require that all the patterns match—it is perfectly ac‐ceptable to the pattern-matching engine for some patterns to matchnothing and for some content to go unmatched.

That makes it easy to build stylesheets that apply to a wide variety ofdifferently structured documents, or to write code that only appliesevent handlers or other processing to elements if and when it finds amatch. It’s a simple message often explained to beginners at the verystart of learning CSS, but it reverberates throughout CSS practice.Stylesheets can be shared, reused, and applied in layers through thecascade that determines which declaration applies where.

10 | CSS Selectors Have Superpowers

Page 19: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Adding to that flexibility, CSS can work with any markup vocabulary.There are some selectors that are tightly bound to HTML expectationsof classes and IDs, but they are mostly syntax sugar. Selecting the samecontent in another vocabulary might require a few more charactersand a bit more processing, but it is always possible and generally easy.

Selectors give developers the freedom to create and use new vocabu‐laries in the browser. Used in style sheets, they let developers tellbrowsers how to present content the browser doesn’t intrinsically un‐derstand. Used in JavaScript, they let developers tell browsers whatbehavior to give new elements and attributes mixed into HTML. Theresult: polyfills, the development style described in “HTML: MovingBeyond the Standard”, which I suspect is the future of web develop‐ment.

Pattern matching has promise for markup processing beyond thebrowser. Historically, that’s mostly been done with XPath and XSLTor with other language combinations rather than CSS selectors, butCSS selectors are spreading even there, on the vectors of JavaScript onthe server and testing tools.

My long-term hope is that the success of CSS selectors will bring de‐velopers to look for other ways to apply pattern matching to theirmarkup, acting as a gateway to more declarative approaches that willadd some much needed flexibility to code and document structures.All these quiet years later, CSS selectors seem to be our best bet forchanging how we write code for the Web.

(You can, of course, extend CSS with tools like SASS and LESS. You’llstill find CSS selectors a key part of that work!)

CSS Selectors Have Superpowers | 11

Page 20: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 21: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

JavaScript: Not as Expected

JavaScript’s ever-growing importance still takes people by surprise.When I post about things JavaScript makes possible, I get pushbackfrom people who refuse to be impressed by JavaScript. Why? Becauseit isn’t what they wanted.

I’ve heard from a variety of quarters about how JavaScript is half Lisp,and terrible either because it dares to be half Lisp or because it onlymanages to be half Lisp. Similarly, as functional programming hasbecome more visible, I’ve heard more from people who think Java‐Script programming is too functional or not functional enough. Peo‐ple disappointed in JavaScript because it doesn’t have strong typing area constant, as are people who find prototypal inheritance perverse.JavaScript syntax doesn’t help.

It’s tempting to tell the story of JavaScript as a series of historical ac‐cidents. Brendan Eich put together LiveScript, applying a variety oftechniques to meet a particular set of needs quickly. Since then, we’vebeen dealing with JavaScript’s shift from a simple object manipulationlanguage to a much broader and more powerful toolkit, unable tochange approach because of the unique dynamics of the browserworld.

The more I think about this, though, the less I think it’s true. JavaScripthas faced competition on various fronts for most of its existence:

• VBScript was an early contender, one that was more approachablefor at least some kinds of development, though it was hobbled byMicrosoft’s ownership.

• Java applets, of course, were supposed to do most of the work wedo today with JavaScript-based web applications. Many of the

13

Page 22: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

applet dreams would have shrunk the Web to simple documentsand containers for applets.

• Flash carried its own banner for years. Of course, ActionScript isitself a dialect of JavaScript, but the tools and environment werevery different. Flash and JavaScript development were generallyseen as competitive, especially as HTML5 added multimedia fea‐tures that had previously required Flash.

Perhaps all of those opponents were flawed, and perhaps JavaScript’subiquity was truly a strange accident.

Perhaps, though, JavaScript actually fits its role well. It’s survived theshift from event handlers specified in the HTML to unobtrusive ap‐proaches. JavaScript syntax has proven extensible enough to supportchained function calls. As discussed in “CSS Selectors Have Super‐powers”, JavaScript tools have adopted CSS selectors to simplify in‐teractions with the document tree, cleaning up one of the longest-standing headaches. JavaScript’s asynchronous event handling haseven found a new home on the server, a key part of Node’s approachto scale. Many of the shiniest parts of HTML5 are also JavaScript APIs,not new markup.

Even if JavaScript isn’t the perfect language so many programmerswould like it to be, it’s proven remarkably flexible, adjusting itself tothe needs of the moment. Its latest act, described in “Will JavaScriptTake Over the Programming World?”, which may keep it from con‐quering the world through ubiquity, is even a disappearing act. Thedevelopers who’ve hated it for years may find its flexibility so powerfulthat they can compile other languages to it, rather than dealing withJavaScript directly.

I wonder, though, whether there’s another round of JavaScript appre‐ciation to come. The years since JavaScript: The Good Parts have seena steady increase in the number of programmers who take JavaScriptseriously. Programming culture hasn’t yet embraced JavaScript as afirst language: web developers may learn it as their first programminglanguage, but programmers tend to start elsewhere. In a perverse way,compilation to JavaScript may increase appreciation of JavaScript’sflexibility (at least among a few who realize what’s happening).

14 | JavaScript: Not as Expected

Page 23: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

JavaScript’s differences, though, don’t seem to have hurt it. Despitesome pieces that seem odd to developers coming from other back‐grounds, those differences have helped JavaScript usage evolve withthe Web.

JavaScript: Not as Expected | 15

Page 24: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those
Page 25: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

From JavaScript toDeclarative Markup

Web architecture separates structured content (markup), presentation(style), and behavior (JavaScript). As recently as a decade ago, manydevelopers worked in all three, but the years since Ajax arrived havebrought more specialization. The rise of JavaScript in particular hasled to approaches that have JavaScript carry the load. I’ve been de‐lighted to see work that suggests a different path forward, one thattakes greater advantage of the flexibility markup offers.

At the Artifact Conference, I was delighted to return to the world ofweb designers. The crowd was full of people who know very well whatJavaScript can add to their site and how they want to include it, butwho also don’t focus on it. JavaScript is just a tool, often even a toolwielded later in the process after the basic framing of the site is com‐plete.

Though the emphasis on design meant that many people were stillenthusiastic about creating comps in Photoshop, one of my favoritetalks included Jen Simmons emphasizing an HTML-first approach topage building: getting the structure of the document right before fo‐cusing on either style or behavior. The unstyled HTML she showedfrom the New York Times made clear the tangles that emerge fromthinking of markup as just a byproduct of the other work done to buildthe site. Other talks explored complex interactions between browsers,markup, and styling needed to make responsive web design work.

Polymer, a project that makes HTML usefully extensible, is a goodplace to explore. Instead of creating a JavaScript program that dealswith the entire page, Polymer focuses on JavaScript modules that deal

17

Page 26: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

with specific markup, markup you can choose. (It can still work withthose programs, of course!)

While I love that Polymer is a surprisingly sudden implementation ofideas I suggested in “HTML: Moving Beyond the Standard”, the part Ilike better is that this approach to problem solving makes it easier toinclude the designers I talked with at Artifact. New markup offeringnew capabilities is great, especially when it can be styled with familiartools. Though it’s early, the Polymer approach promises a much easierconversation between designers, programmers, and the developerscombining aspects of both.

Does this new markup extensibility mean that JavaScript developerswill have less to do as modularization simplifies sharing? I don’t thinkso. In Extend the Web Forward, Yehuda Katz suggests that there is alot more extending to do:

When the browser has good extension points (or any extensionpoints, really), we live in a virtuous cycle…If things are working well, JavaScript library authors write new de‐clarative APIs that the browser can roll in. Nobody wants to writeeverything using low-level calls to canvas, but we’re happy that canvaslets us express low-level things that we can evolve and refine.

Katz doesn’t claim it will be easy. He worries about “extension pointsthat can be performance footguns.” He does, however, see the constantflow from imperative JavaScript APIs to more declarative approachesas the path forward. To me, that seems like the right way to balanceflexibility with usability.

18 | From JavaScript to Declarative Markup

Page 27: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Toward Responsive WebProgramming

“Expect the unexpected” has long been a maxim of web development.New browsers and devices arrive, technologies change, and thingsbreak. The lore of web development isn’t just the technology: it ad‐dresses the many challenges of dealing with customers who want tolock everything down.

Matt Griffin (and a lot of others) reminded me of these difficulties atArtifact, and his Client Relationships and the Multi-Device Webbrings it home for designers.

Is there room for programmers to tell a similar story?

I don’t mean agile. Agile development is difficult enough to explain toclients, but applications that adapt to their circumstances are a separateset of complications. Iterating on adaptable behaviors may be moredifficult than iterating on adaptable designs, but it opens new possi‐bilities both for applications and for the evolution of the Web.

Responsive Web Design is (slowly) becoming the new baseline, givingdesigners a set of tools for building pages that (usually) provide thesame functionality while adapting to different circumstances. Pro‐grammers sometimes provide different functionality to differentusers, but it’s more often about cases where users have different priv‐ileges than about different devices and contexts.

Adjusting how content displays is complex enough, but modifyingapplication behavior to respond to different circumstances is moreunusual. The goal of most web development has been to provide asingle experience across a variety of devices, filling in gaps whenever

19

Page 28: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

possible to support uniformity. The history of “this page best viewedon my preferred browser” is mostly ugly. Polyfills, which I think havea bright future (as described in “HTML: Moving Beyondthe Standard”), emerged to create uniformity where browsers didn’t.

Browsers, though, now provide a huge shared context. Variations exist,of course, and cause headaches, but many HTML5 APIs and CSS3features can work nicely as supplements to a broader site. Yes, youcould build a web app around WebRTC and Media Capture andStreams, and it would only run on Firefox and Chrome right now. Butyou could also use WebRTC to help users talk about content that’svisible across browsers, and only the users on Firefox and Chromewould have the extra video option. The Web Audio API is also a goodcandidate for this, as might be some graphics features.

This is harder, of course, with things like WebSockets that providebasic functionality. For those cases, polyfills seem like a better option.Something that seems as complicated and foundational as Index‐edDB could be made optional, though, by switching whether data isstored locally or remotely (or both).

HTML5 and CSS3 have reawakened web development. I’m hopingthat we can develop new practices that let us take advantage of thesetools without having to wait for them to work everywhere. In the longrun, I hope that will create a more active testing and developmentprocess to give browser vendors feedback earlier—but getting therewill require changing the expectations of our users and customers aswell.

20 | Toward Responsive Web Programming

Page 29: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Will JavaScript Take Over theProgramming World?

Last July, I had to give an impromptu talk. What came out, much tomy surprise, was roughly: “JavaScript will dominate the programmingworld.” I didn’t say that JavaScript would dominate through sheerpopularity—JavaScript may in fact top the list of languages disliked byprogrammers, because so many programmers use it as a strictly sec‐ondary language beside their preferred server-side toolkit.

Instead, I argued, as you’ll see in “Concentration: The Wrong Story”on page 21, that JavaScript would win by ubiquity, offering a solutionthat fits well enough in both clients and servers. While I still thinkJavaScript could indeed “fit well enough,” the winds have changed, andJavaScript may be about to surrender its ubiquity advantage, as you’llsee in “Dispersion: A More Likely Story?” on page 24.

Concentration: The Wrong StoryAfter decades of a Cambrian explosion, we may finally see a concen‐tration in the use of a few programming languages and a correspond‐ing decline of many others, leaving us with three main families ofprogramming languages. (Remember, this story is wrong.)

C and its immediate relatives will always be with us, providing a thinabstraction layer just above the processor. Functional languages thattrade off ease of use in favor of extreme reliability, scalability, andmanageability will continue to thrive in a small but ever-more impor‐tant space. The biggest changes, though, will happen to the currentlydiverse general-purpose languages.

21

Page 30: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

General-purpose languages, the tools that programmers have used toquickly assemble programs without having to sweat the details ofmemory management and data structures, are approaching a turningpoint. There is nothing intrinsically wrong with Perl, Python, Ruby,PHP, Java, C#, or many others, and they will continue to be used for along time. However, their growth rates are going to shrink dramati‐cally.

What innovation could unseat those champions? It’s “the VB of theWeb,” a language that was patronized and dismissed for over a decade.JavaScript may not have had much respect for a very long time, but ithas two major advantages over all of its general-purpose competitors:Ubiquity

JavaScript is available on practically every computer sold today,and any programmer who’s gone near the Web has at least thoughtabout it.

PowerThe JavaScript renaissance continues to demonstrate that thislanguage is extremely capable, especially in the ever-growingnumber of cases where asynchronous communications are nec‐essary.

JavaScript snuck in. For a long time, “write once run anywhere” wassupposed to mean Java, with its armies of virtual machines for everyplatform. The browser was just a window into a server-based world,with JavaScript providing a few key features on the client. As devel‐opers realized that the Web was the easiest way to create user interfacesfor shared data, more and more programming activity shifted awayfrom classic GUI implementation to building web applications. Asmore and more Java development fell back to the server, JavaScriptsolidified its hold on the client.

While the Dynamic HTML boomlet of the late 90s vanished into thedot-com bust, Ajax returned JavaScript to prominence in 2005. Doug‐las Crockford’s JavaScript: The Good Parts made it clear that JavaScriptwas a first-class programming language, even if its take on objects wasunconventional. Growing demand for more desktop-like user expe‐riences led to massive growth in JavaScript programming, with moreprocessing happening in the browser. That often (though not always)led to simplification on the server side.

22 | Will JavaScript Take Over the Programming World?

Page 31: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

Having achieved ubiquity as THE language (pretty much the onlylanguage) for client-side web programming, JavaScript is now poisedto take over the server as well. It is not just possible to program theserver-side components of a web application in JavaScript, but Java‐Script has certain key advantages other languages can’t compete with:

• JavaScript’s years of use in interfaces created a dominant callbackstyle that works efficiently in pretty much any asynchronous com‐munications situation.

• Browsers now run on an incredibly wide variety of devices, fromcellphones with slow CPUs and lousy bandwidth to speedy ma‐chines with lots of bandwidth. Using JavaScript lets applicationsdecide where they want the code to run, and new frameworks(notably but not exclusively Mojito) can decide based on a givensituation whether JavaScript should run on the client or the server.

It is probably possible to create a language with as much support forasync as JavaScript, and a better syntax. It probably also makes senseto compile that language to JavaScript, as both CoffeeScript and Dartdo.

The second advantage is much, much harder to overcome. It’s certainlypossible for something like GWT to compile Java to JavaScript, but it’sa difficult thing to sustain. RJS (Ruby compiled to JavaScript) becamea dead end pretty quickly. JavaScript may be a great target for com‐pilers, as CoffeeScript and Dart are demonstrating, but those languag‐es typically retain many of the restrictions and values of JavaScript.

The JavaScript community itself is evolving to support these new pos‐sibilities. Node is the hot and new server-side environment (completewith surprising support from Microsoft), but perhaps more impor‐tantly, it’s spawning an ever-growing number of extensions and frame‐works. Most of those are small pieces, but “full-stack” frameworks,notably Meteor, are emerging to cover the entire range of tasks fromquerying databases to helping users interact with that data.

Wait five years, and there won’t be much good reason to use otherlanguages to build web applications. Wait 10 years, and you’ll see ap‐plications written in other languages migrating to JavaScript becauseof the enormous ecosystem it’s building. Because so many program‐mers use JavaScript at least “part-time,” it’s not hard to find program‐mers for JavaScript projects. JavaScript’s lack of a corporate master (a

Concentration: The Wrong Story | 23

Page 32: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

difficulty in its early years) gives it an advantage moving forward be‐cause users don’t have to fear corporate agendas.

Other languages will probably not go extinct, but it will be much moredifficult for them to grow. My suspicion would be that they find smallerniches, with Python perhaps holding on in the sciences, Ruby in ex‐perimental development, Java and C# in some corporate systems, andPerl in text processing and data munging. They will all still be good atwhat they do, but will face sharper competition.

I was, of course, wrong.

Dispersion: A More Likely Story?I no longer forecast JavaScript taking over the general-purpose lan‐guage space. It’s not because polyglot (multilanguage) programmingis more fun or even more powerful for most cases. It’s because I waswrong about the side effects of compiling to JavaScript.

When I first told this story, compilation to JavaScript was exciting buttricky. It was spreading from GWT to Dart to ClojureScript to Cof‐feeScript, but it seemed likely to always remain special purpose, buffer‐ing a larger shift toward JavaScript but incapable of slowing down agrowing shift.

Over the last few months, though, I’ve been surprised by continuingconversations about JavaScript as a new assembly language—certainlymore approachable than my distant memories of 6502, but similarlyflexible. Asm.js broadened that conversation dramatically. While I re‐main uncertain that it will be the one true approach, it makes it veryclear that the compilation approach can be more generic than I hadthought possible.

Compilation approaches mean that “the JavaScript way” will no longerbe the only way to do things in the spaces where JavaScript currentlydominates. This frees developers who don’t especially like the Java‐Script way to work with approaches that they’re more comfortablewith. Even developers who are fond of JavaScript may take the op‐portunity to experiment with something different as toolsets grow andit becomes easier to do.

24 | Will JavaScript Take Over the Programming World?

Page 33: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

The Cambrian explosion I mentioned earlier may be returning—toJavaScript itself. Asm.js and related work moves programming an‐other layer up the abstraction stack. Our processors seem capable ofhandling the known inefficiencies, and our toolsets seem prepared foranother bout of rapid evolution.

Dispersion: A More Likely Story? | 25

Page 34: The Web Platform - SMLUGThe Web Platform: Building a Solid Stack of HTML, ... Both HTML markup and CSS stylesheets are declarative, making ... The best part, though, is that those

About the AuthorSimon St.Laurent is Senior Editor at O’Reilly Media, Inc., focusingprimarily on JavaScript and web-related projects. He is co-chair of theFluent and OSCON conferences. He’s authored or coauthored booksincluding Introducing Elixir, Introducing Erlang, Learning Rails 3,XML Pocket Reference, Third Edition,, XML: A Primer, and Cookies.