Survive JavaScript - Strategies and Tricks

Preview:

DESCRIPTION

Getting started with JavaScript can be somewhat challenging. Especially given how fast the scenery changes. In this presentation I provide a general view of the state of the art. Besides this I go through various JavaScript related tricks that I've found useful in practice. survivejs.com is a companion site of the presentation and goes on further detail in various topics. The original presentation was given at AgileJkl, a local agile conference held in Central Finland.

Citation preview

Survive JavaScriptStrategies and Tricks

Juho Vepsäläinen

AgileJkl 2013

What's in Store?

Web Development Strategies

JavaScript Tricks

Conclusion

·

How Did We Get Here

Where Are We Now

Where Are We Headed

-

-

-

·

Node.js

Development Tools

Structuring Code

Finding Libraries

Testing

-

-

-

-

-

·

Web Development Strategies

Strategy for Goldfishes

Source: HikingArtist.com (CC BY-NC-ND)

Strategy for the Rest of Us

How Did We Get Here

Ten Days to JavaScript

1995 - Brendan Eich's ten days → Mocha

Known as LiveScript till the marketing folks changed thename

Even though has Java in name, completely different

Influence of Java 1.0 visible mainly in Math and Timemodules

Prototypal inheritance a lá Self

Dynamic, flexible, lambdas

Scheme in disguise - See The Little JavaScripter byCrockford

·

·

·

·

·

·

·

A Bit of JavaScript

var helloAgileJkl = hello.bind(undefined, 'AgileJkl!');

helloAgileJkl();

function hello(target) { console.log('Hello ' + target);}

// or could justconsole.log('Hello AgileJkl!');// to avoid over-engineering!

JAVASCRIPT

Web - From Documents to Applications

Web as a Document Platform

Improved Interactivity

Web as an Application Platform

·

1995 - Brendan Eich's ten days

1999 - ES3 (modern baseline), Mozilla established

-

-

·

2005 - AJAX, dynamic loading (search for instance)

2008 - RIP ES4, parts of HTML5 emerge, Chrome (V8)

2009 - ES5, Chrome OS, Node.js

-

-

-

·

2012 - HTML5 well supported (interesting JS APIs)-

Source: Brendan Eich at Strange Loop '12

JavaScript Has Traction

Source: Redmonk

Crockford

Source: superfluity (CC BY-NC-SA)

The Good Parts vs. The Rest

Source: Oльга + Haфaн (CC BY)

Recap

JavaScript, an unlikely winner

Language of the web

More powerful than it seems

Web isn't just about documents, now applications too

·

·

·

·

Where Are We Now

Elements of Web Applications

Logic

JavaScript

CoffeeScript

CoffeeScript is a little language that compiles into JavaScript. Underneath that awkwardJava-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt toexpose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into theequivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript libraryseamlessly from CoffeeScript (and vice-versa). The compiled output is readable and pretty-printed,passes through JavaScript Lint without warnings, will work in every JavaScript runtime, and tendsto run as fast or faster than the equivalent handwritten JavaScript.

Latest Version: 1.6.2

sudo npm install -g coffee-script

Overview

CoffeeScript on the left, compiled JavaScript output on the right.

# Assignment:number = 42opposite = true

var cubes, list, math, num, number, opposite, race, square, __slice = [].slice;

TABLE OF CONTENTS TRY COFFEESCRIPT ANNOTATED SOURCE

Dart

(/)

Dart brings structure to web app

engineering with a new language,

libraries, and tools. Read about our

new M4 release!

(http://news.dartlang.org/2013/04/core-

libraries-stabilize-with-darts-

new.html)

News (http://news.dartlang.org/) TweetTweetSearch Docs Tools Resources Development

TypeScript

Get TypeScript Now

TypeScript is a language for application-scale JavaScript development.TypeScript is a typed superset of JavaScript that compiles to plainJavaScript.Any browser. Any host. Any OS. Open Source.

Starts from JavaScript, Ends withJavaScriptTypeScript starts from the syntax and semantics that millions of JavaScript developers knowtoday.

learn play get it run it join in

And many others

altJS

Markup

HTML

Jade

doctype 5html(lang="en") head title= pageTitle script(type='text/javascript') if (foo) { bar() } body h1 Jade - node template engine #container if youAreUsingJade

<!DOCTYPE html><html lang="en"> <head> <title>Jade</title> <script type="text/javascript"> if (foo) { bar() } </script> </head> <body> <h1>Jade - node template engine</h1>

View Documentation

Node Template Engine

Handlebars

Handlebars provides the power necessary to let you build semantic templateseffectively with no frustration.

Mustache templates are compatible with Handlebars, so you can take a Mustachetemplate, import it into Handlebars, and start taking advantage of the extra Handlebarsfeatures.

Download: 1.0.0-rc.3Download: 1.0.0-rc.3Download: runtime-1.0.0-rc.3

Getting Started

Transparency

Examples

Assigning valuesAssigning values

Iterating over a listIterating over a list

Nested listsNested lists

Nested objectsNested objects

Transparency is a minimal template engine for jQuery. It maps JSONTransparency is a minimal template engine for jQuery. It maps JSONobjects to DOM elements with zero configuration. objects to DOM elements with zero configuration. Just call .render()Just call .render()

CoffeeScript JavaScript

hello = hello: "Hello!" hi: "<i>Hi there!</i>" span: "Goodbye!"

$('.container').render hello

Jade HTML

.container #hello .hi span

Styling

CSS

LESS

Write some LESS:

@base: #f938ab;

.box-shadow(@style, @c) when (iscolor(@c)) { box-shadow: @style @c; -webkit-box-shadow: @style @c; -moz-box-shadow: @style @c;}.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) { .box-shadow(@style, rgba(0, 0, 0, @alpha));}.box { color: saturate(@base, 5%); border-color: lighten(@base, 30%); div { .box-shadow(0 0 5px, 30%) }}

Compile to CSS:

npm install -g lesslessc styles.less styles.css

version 1.3.3changelog

The dynamic stylesheet language.

LESS extends CSS with dynamic behavior such asvariables, mixins, operations and functions.

LESS runs on both the server-side (with Node.jsand Rhino) or client-side (modern browsers only).

overview   usage   language   function reference   source   about   try it now! FollowFollow

SASS

$ gem install sass $ mv style.css style.scss $ sass --watch style.scss:style.css

About Tutorial Documentation Blog Try Online

Latest Release: Media Mark (3.2.7)What's New?

Download

Editor Support

Development

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the commandline tool or a web-framework plugin.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and isa superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSSfiles use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’sterseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets

Twitter Bootstrap

Bootstrap (./index.html)

BootstrapSleek, intuitive, and powerful front-endframework for faster and easier web

development.

Download Bootstrap (assets/bootstrap.zip)

Zurb Foundation

Features (grid.php) Add-ons (templates.php) Case Studies (case-jacquelinewest.php) Docs (docs) Training (training.php)

Foundation (http://foundation.zurb.com)

FoundationThe most advanced responsivefront-end framework in the world.

Download Foundation 4 (download.php)

10.9k stargazers(http://github.com/zurb/foundation)

@foundationzurb(http://twitter.com/foundationzurb)

Data

Data

Usually handled with a backend or external services(Disqus for comments for example)

RESTful interfaces (client-side MVC)

Local caching (localStorage ie.)

Offline usage (replication, PouchDB)

·

·

·

·

Big Data

Source: infocux Technologies (CC BY-NC)

Recap

Logics are violet

Markups are blue

Styling is sweet

And so is data

Where Are We Headed

Enlightenment

Source: michael.heiss (CC BY-NC-SA)

Source: Augie Schwer (CC BY-SA)

Source: letmehearyousaydeskomdeskom (CC BY-SA)

Shim

a thin often tapered piece of material (as wood, metal, orstone) used to fill in space between things (as for support,leveling, or adjustment of fit)

Source: Merriam-Webster, esagor (CC BY-NC)

caniuse.com

Index Tables

Can I use...Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.

Latest update: Three new features added: Shadow DOM, WebP images & Intrinsic width & height (April 3, 2013)

Search:border‑radius, WebGL, woff, etc

CSS@font­face Web fontscalc() as CSS unit value2.1 selectorsCountersFeature QueriesFilter EffectsGenerated contentGradientsGrid LayoutHyphenationinline­blockMasksmin/max­width/heightoutlineposition:fixedRegions

HTML5Audio elementCanvas (basic support)Color input typecontenteditable attribute (basic support)Datalist elementdataset & data­* attributesDate/time input typesDetails & Summary elementsDownload attributeDrag and DropForm validationHTML5 form featuresinput placeholder attributeNew semantic elementsNumber input typeOffline web applications

SVGInline SVG in HTML5SVG (basic support)SVG effects for HTMLSVG filtersSVG fontsSVG fragment identifiersSVG in CSS backgroundsSVG in HTML img elementSVG SMIL animationAll SVG features

Otherasync attribute for external scripts

TOPSuggestions  Feed  Twitter

I mpo rt s tats FA Q Reso u rces Embed

564

Source: T.R.G. (CC BY-NC-SA)

Rise of the Mobile

Android

Source: San Diego Shooter (CC BY-NC-ND)

Firefox OS, Jolla etc.

Source: Brian LeRoux (CC BY-NC-SA)

Native vs. HTML5

Native apps still have their advantages

JS is a good alternative for prototyping

Available technology keeps maturing

And we'll likely see better platform support

·

·

·

·

Web Architectures

Blog (Static Site)

JSter (Portal)

Future JSter?

Other Considerations

What belongs to server, what to client and why (businessgoals)

Client-side MVC is not a silver bullet

Basecamp's experiences (hint: pushState, aggressivecaching)

Synchronization, offline usage, skills, time, budget...

Fashion. Techs come and go

Up and coming? Mixed approaches. Examples: Meteor,Derby, mojito, rendr

·

·

·

·

·

·

Recap

Web dev is as hard as you make it

Especially on the bleeding edge

Fortunately a bit of tape fixes anything

Mobile on the rise, native HTML5 apps not mainstream yet

Web architectures - from monoliths to distributed

·

·

·

·

·

JavaScript Tricks

Node.js

Trends

Source: Google Trends

Packages per Year

Python: 29,720 packages / 22 years = 1351 packages / year

Ruby: 54,385 packages / 18 years = 3022 packages / year

Node.js: 26,966 packages / 4 years = 6742 packages / year

·

·

·

Source: Gregg Gaines

Server Using Callbacks

var http = require('http');

http.createServer( function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello AgileJkl!\n'); }).listen(8000);

JAVASCRIPT

Short and sweet

Express is very popular for more complex cases

·

·

Server Using EventStreams

var http = require('http');

var s = new http.Server();

s.on('request', function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello AgileJkl!\n');});

s.listen(8000);

JAVASCRIPT

Viable alternative to callbacks at times

More info at Node.js: Patterns and Opinions by @izs (theNode guy)

·

·

Recap

Excellent for prototyping

Strong ecosystem thanks to NPM

Develops at a blistering pace

·

·

·

Development Tools

Vim, Emacs, Sublime Text, WebStorm...

Chrome Inspector

See also Firebug·

Source: Chrome DevTools

LiveReload

LiveReload 2 proudly presents…

The Web Developer Wonderland(a happy land where browsers don't need a Refresh button)

CSS edits and image changes apply live.

CoffeeScript, SASS, LESS and others just work.

Citizenship is granted through the Mac App Store.Windows permanent residency issues are being worked out,temporary stay already allowed.

JSLint

clear

Read the instructions.Set the options.Enjoy The Good Parts.Donate.

The JavaScript Code Quality Tool

Edition 2013-04-09

Source

// Paste quality code here

See also JSHint·

jsFiddle

Run Save TidyUp JSHint Login/Sign up

No‑Library (pure JS)

onLoad

Tip JSFiddle

Frameworks & Extensions

Fiddle Options

External Resources

Languages

Ajax Requests

Examples

Legal, Credits and Links

Gittip

Keyboard shortcuts?

1

1

1HTML

JavaScript

CSS

Result

Others: jsbin, jsdo.it, ...·

Cloud9 IDE

Cloud9 IDE - Online IDEGive us a shout out: Share on twitter Share on Google Share on facebook Share on emailSign up

Sign outUsername or e‑mail Password Sign In

Keep me signed inForgot password? Resend activation email

Or sign in instantly with:

NEWS: The Changelog of March: Stability, Performance, Features

Hey there! Over the past month we have worked very hard on improving the stability and performance of our service. In addition, we also worked onsome interface changes ...read the full article | see all articles

PricingFeaturesBlogCompany

Company•Board Members•Jobs•Press•Contact

Node.jsNode.js•Nodebits.com•NodeManual.org

SupportSupport•Status•Documentation

Your code anywhere, anytime...

Recap

Traditional editors and IDEs are fine

Additional tooling available, use it

Future in the web?

·

·

·

Structuring Code

The Anti-Pattern

<script src='jquery-current.js' type='text/javascript'></script><script src='sorttable.js' type='text/javascript'></script><script src='scripts.js' type='text/javascript'></script><script src='miniCalendar.js' type='text/javascript'></script>

HTML

Each include has to be defined by hand

Brittle and prone to error, especially with large codebases

Does not encourage to modularity

Hard to reuse

·

·

·

·

Concatenate Scripts

<script src='application.js' type='text/javascript'></script> HTML

Old skool but works

Less overhead at HTML

Still, running into dependency order problem atconcatenation

Possible to complement by loading scripts (ie. jQuery)from a CDN

Nevertheless a step forward

·

·

·

·

·

RequireJS and AMD + Bower

<script data-main="scripts/main" src="scripts/require.js"></script> HTML

define(['jquery', './math'], function($, math) { return { // exports vector: function() {...} };});

JAVASCRIPT

Modular, asynchronous approach

Includes define overhead (possible to mimic Node.jsconvention, though)

Optimizer resolves dependencies and creates build(loadable with Almond)

Configuration complex at times

·

·

·

·

Browserify + NPM

<script src='application.js' type='text/javascript'></script> HTML

var $ = require('jquery');var math = require('./math');

exports.vector = function() {...};

JAVASCRIPT

Allows to use Node.js module convention (CJS)

Better yet allows to hook into NPM ecosystem!

Still fairly bleeding edge

·

·

·

Recap

No official module system yet (ES6?)

Many alternatives (AMD, CJS etc.)

browserify looks promising (NPM!)

·

·

·

Finding Libraries

NPM

Search PackagesNODE.JS HOME

DOWNLOAD

ABOUT

NPM REGISTRY

DOCS

BLOG

COMMUNITY

LOGOS

JOBS

Node Packaged ModulesTotal Packages: 28 067

907 584 downloads in the last day9 157 954 downloads in the last week

33 188 669 downloads in the last month

Patches welcome!

Any package can be installed by using npm install.

Add your programs to this index by using npm publish.

Recently Updated0m jspm

Most Depended Upon2740 underscore

Create Account | Login

Bower

Bower componentsDiscover Bower (http://bower.io)components

Check out some of my other

projects

Focus

(https://github.com/sindresorhus/focus),

JsRun

(https://github.com/sindresorhus/sublime-

jsrun), sublime-

editorconfig

(https://github.com/sindresorhus/editorconfig-

sublime), GitHub-Notifier

(https://github.com/sindresorhus/GitHub-

Notifier), Pure

(https://github.com/sindresorhus/pure),

quora-unblocker

(https://github.com/sindresorhus/quora-

unblocker)

screenfull.js (https://git…

stringify-object (https:/…

Featured components

Fullsc…

API

wrap…String…

an

flight-storage (https://gi…

spice.css (https://github…

Latest components

Store…

JSON

dataBasic…

dry css

min.js (https://github.co…

angularjs-ordinal-filter …

Hot components

Super…

mini…

select…Angul…

Ordinal

(https://github.com/sindresorhus/bower-components)

JSwiki

JSwiki 2 TweetTweet 59 EditEdit

Hi there! Welcome to jswiki.

This wiki indexes libraries and resources available for JavaScript. In addition it provides some starting pointsfor newbies in form of Beginner's Resources. In case you want to contribute, do take a look at Meta first forsome extra pointers. Happy hacking!

IMPORTANT! jster.net is a spiritual successor of jswiki. There is more content but thesite is less of a wiki. jswiki will remain here as more of a communal alternative. Inaddition you might want to check out the following:

JSwikiEssentials

Multimedia

Graphics

Data

UI

Utilities

Development

Applications

jsgamewiki Microjs

EveryJS JSDB

JSPkg

Recap

No need to just Google it

Package managers (esp. NPM) make your life easier

Avoid NIH and use existing solutions

·

·

·

Testing

Unit Testing

assert(title('HELLO WORLD!') === 'Hello World!');assert(title('Hello world!') === 'Hello World!');assert(title('hi') === 'Hi');assert(title() === undefined);

function title(s) { return s && s.split(' ').map(capitalize).join(' ');}

function assert(s) { if(!s) throw new Error('Assertion failed!');}

JAVASCRIPT

Popular alternatives: Jasmine (BDD), Mocha, QUnit·

Fuzz Testing

// function to test, note annotationvar title = annotate('title', 'Returns given string in a title format.') .on(is.string, function(s) { return s && s.split(' ').map(capitalize).join(' '); }).satisfies(is.string);

// testing an invariantfuzz(title, function(op, str) { var parts = op(str).split(' ');

return parts.map(fst).map(isUpper).filter(id).length == parts.length;});

JAVASCRIPT

Up and coming (hopefully)·

Source: bebraw/annofuzz

Testling

testling-cirun your browser tests on every push

write some tests

Use the test runner you like best!

The only thing your test runner needs to do is to produce TAP outputon console.log or process.stdout. Here's an example project usingmocha.

You can also use tape to output TAP output in browsers and in node.Here is what a simple tape test looks like:

var test = require('tape');var myCode = require('../my_code.js');

test('make sure my code works', function (t) { t.plan(2); t.equal(myCode.beep(5), 555);

Browserling

interactive cross-browser testing

http://

3.0 3.5 3.6 4.0 5.0 6.07.0 8.0 9.0 10.0 11.0 12.013.0 14.0 15.0 16.0 17.0 18.0

19.0 nightly

create account sign in

Browserstack

Live, Web-Based Browser TestingInstant access to all desktop and mobile browsers.

Say goodbye to your setup of virtual machines and devices.

Free Trial

Sign up for free

Full Name

Email

Password

No credit cardNo credit cardrequired. We promise.required. We promise.

Support Pricing Free TrialResources Sign inL i v e

Chaos Monkey

Source: Jeff Atwood - Working with the Chaos Monkey

AB Testing

Source: TheBusyBrain (CC BY)

Recap

Test your JS

Browser differences bring their own challenge

Future in continuous integration (Travis and co.)

Fail constantly to avoid failure

·

·

·

·

Conclusion

Conclusion

JS - the most valuable language you don't know yet

A target for tool and language development

Not without its quirks but still manageable

The most important language of this decade?

·

·

·

·

Survive JS - The Guide

Survive JSHave you ever felt lost in the JavaScript jungle? If so, you are in the right place. The purpose of this guideis to provide you with sharp implements that help you survive and perhaps thrive even. Even seasonedJavaScript explorers might find a trick or two to apply in practice.

As it is very possible I have not reached omnipotence yet, I encourage you to submit issues. This way wecan make the guide to serve you better.

I am well aware there are other excellent resources out there. Of these I would like to mention EloquentJavaScript and JavaScript Garden in particular. I have listed various beginner's resources over at JSwiki,the predecessor of JSter.

Table of ContentsA Misunderstood Language? - What is the essence of JavaScript? Why is it relevant?

Current State - What is the current state of JavaScript and the ecosystem?

Language Features - What the language looks like? How to use it effectively?

EditEdit

TweetTweet 0

0

Table of Contents

Survive JS

Thank You!

twitter @bebrawwww www.nixtu.infogithub github.com/bebraw

Recommended