@rob_rich

A Dozen
JavaScript
Libraries

by Rob Richardson

@rob_rich

http://robrich.org/

October 2, 2013

About Me

Rob Richardson is principal of Richardson & Sons, LLC, builder of ASP.NET and Node solutions for small- to medium-sized businesses. Rob has a BFA and MSCIS, and has been building software in .NET and HTML for over a dozen years, and frequently enjoys sharing his passion for software development at user groups and community events. Follow Rob at @rob_rich or on his blog at http://robrich.org/.

Libraries

Why do we need JavaScript libraries?

  • HTML and JavaScript haven't really changed since 1992
  • I want to stand on the shoulders of giants

Libraries

Why should we avoid JavaScript libraries?

  • It bloats the page
  • Additional HTTP Requests cause slower page load

Use Libraries Correctly

Use libraries when the download / page-init time
is worth the shorter dev time

Don't use libraries when a few
simple lines could do the same thing

A dozen libraries

Ready?

jQuery

What is it

An animation, effects, and ajax library

Smooths over inconsistencies in browser DOMs

Size

81.6k

Strengths

  • Used by nearly everyone
  • Trivial to learn, trivial to use

Weaknesses

  • Very large
  • Most modern browsers have caught up

jQuery

Example


$('#save').click(function () {
  var name = $('#name').val();
  $.post('/service', {name: name}, function (r) {
    $('#status').text('status: '+r.message);
  });
});
					

Lo-Dash

What is it

Object and array tools (think LINQ)

Feature compatible, speed optimized version of underscore

Size

26.1k

Strengths

  • Great bredth of features
  • Pretty good documentation
  • Most Underscore uses have switched to Lo-Dash

Weaknesses

  • Examples aren't always clear

Lo-Dash

Example


var stooges = [
  { name: 'larry', age: 20 },
  { name: 'curly', age: 30 },
  { name: 'moe', age: 40 }
];
var match = _.where(stooges, { age: 40 });
// [{ name: 'moe', age: 40 }]
var names = _.pluck(stooges, 'name');
// ['larry', 'curly', 'moe']
					

Handlebars

What is it

1-way templating

(super-set of Mustache)

Size

71.0k

Strengths

  • Can load templates from URL or from script tag
  • Can embed simple logic in templates

Weaknesses

  • If embedding templates in server-processed templates, need to uber-escape things

Handlebars

Example


<script id="entry-template" type="text/template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
      {{body}}
    </div>
  </div>
</script>
					

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
var context  = {title: "My New Post", body: "This is my first post!"}
var html     = template(context);
$("#page").html(html);
					

Modernizr

What is it

Browser feature detection, creates HTML5 elements for old-ie

Size

15.0k*

*build custom version with only the feature tests you need

Strengths

  • Easily shim in content only when needed
  • Can embed simple logic in templates

Weaknesses

  • Can't leverage CDN when using it correctly

Modernizr

Example


Modernizr.load({
  test: (window.JSON && JSON.stringify && JSON.parse),
  nope: "//cdnjs.cloudflare.com/ajax/libs/json3/3.2.5/json3.min.js"
});
					

.incompatible {
  display: none;
}
.no-svg .incompatible {
  display: block;
}
					

Moment

What is it

Easily parse, format, and calculate dates

Size

18.7k

Strengths

  • Supports more date parsing formats than built-in Date

Weaknesses

  • Date math depends on (broken) built-in Date object
  • Format parameters are different than most date libs

Moment

Example


var d = moment('2013-02-04T10:35:24-08:00');
var s = d.format('M/D/YYYY h:mm:ss A');
// 2/4/2013 10:35:24 AM
var a = d.fromNow();
// 1 year ago
					

Normalize.css

What is it

Gently normalize CSS inconsistencies between browsers

Size

7.3k

Strengths

  • Used by Twitter Bootstrap, HTML5 Boilerplate, YUI, etc, etc
  • Gentler than reset.css's sledge hammer approach
  • Preserves many browser defaults

Weaknesses

  • Will you override these styles anyway?

Normalize.css

Example


<link rel="stylesheeet" src="normalize.css" />
					

demo

Twitter Bootstrap

What is it

CSS grid layout, elegantly restyle standard controls

Size

257k

Strengths

  • Takes the fuss out of CSS
  • Responsive and mobile friendly out-of-the-box

Weaknesses

  • Static top nav is the sign that it's overused

Twitter Bootstrap

Example


<div class="row">
  <div class="col-md-8">two-thirds</div>
  <div class="col-md-4">one-third</div>
</div>
					

demo

jQuery UI

What is it

Control library built atop jQuery

Size

285k

Strengths

  • Free is a great pricetag
  • Typically as easy as jQuery

Weaknesses

  • A bit bloated
  • Some controls have unusual interfaces

jQuery UI

Example


$("#date").datepicker();
					

jQuery validate

What is it

Data validation framework

Size

20.5k

Strengths

  • Drop-dead easy

Weaknesses

  • ASP.NET destroys it
  • HTML5 can do much of this now

jQuery validate

Example


<form id="commentForm">
  <input id="name" name="name" minlength="2" type="text" required placeholder="Name *" />
  <input id="email" type="email" name="email" required placeholder="Email *" />
  <input id="url" type="url" name="url" />
  <label for="comment">Comment *</label>
  <textarea id="comment" name="comment" required></textarea>
  <input class="submit" type="submit" value="Submit"/>
</form>
<script>
$("#commentForm").validate();
</script>
					

Backbone

What is it

MV*-like framework provides structure and separation

Size

19k

Strengths

  • Source is very, very well documented
  • Pattern yields very small functions
  • Very unopinionated
  • Built-in url router

Weaknesses

  • Easy to use the DOM ineficiently

Backbone

Example


var DocumentRow = Backbone.View.extend({

  tagName: "li",

  className: "document-row",

  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  }

  render: function() {
    ...
  }

});
					

Angular

What is it

MV*-framework, 2-way data-binding, fake web parts

Size

78.9k

Strengths

  • Drop-dead simple data binding
  • Great patterns for well organized code
  • Built-in url router, ajax, and DI

Weaknesses

  • Too much voodoo, dificult to debug

Angular

Example


<html ng-app>
  <head>
	<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
	<script src="script.js"></script>
  </head>
  <body>
	<div ng-controller="HelloCntl">
	  Your name: <input type="text" ng-model="name" value="World"/>
	  Hello {{name}}!
	</div>
  </body>
</html>
					

function HelloCntl($scope) {
  $scope.name = 'World';
}
					

JSHint

What is it

Check JavaScript for common errors in IDE or CI

Community-maintained fork of JSLint

Size

295k (not deployed)

Strengths

  • Great integration into most IDEs
  • Errors are descriptive and friendly

Weaknesses

  • Plethora of options means non-trivial on-ramp

Mocha

What is it

JavaScript testing harness

Size

250k (not deployed)

Strengths

  • Doesn't polute global namespace like QUnit
  • Can use any assertion framework: should, expect, chai, etc.
  • Very intuitive async testing

Weaknesses

  • Hard to test for unhandled exceptions

Mocha

Example


describe("A suite", function() {
  it("contains spec with an expectation", function() {
    "the answer".should.be("the answer");
  });
});
					

RequireJS

What is it

AMD module loading framework

Size

14.7k

Strengths

  • Unlike CommonJS works asynchronously
  • Automatically resolves and inject dependencies
  • r.js compiles into single, minified deployment script

Weaknesses

  • It's a major paradigm shift
  • Not universally supported, so some libs polute global scope

RequireJS

Example


define(['require', 'dependency1', 'dependency2'], function (require) {
  var dependency1 = require('dependency1'),
      dependency2 = require('dependency2');

  return function () {};
});
					

Rafael

What is it

SVG Charting library

Size

89.2k

Strengths

  • Great interactivity

Weaknesses

  • Browser must support SVG
  • Library is low-level, so you'll likely write a helper wrapper
Library Size
jQuery 81.6k
Lo-Dash 26.1k
Handlebars 71.0k
Modernizr 25.0k
Moment 18.7k
Normalize.css 7.3k
Twitter Bootstrap 257k
jQuery UI 285k
jQuery validate 20.5k
Backbone 19k
Angular 78.9k
JSHint 295k
Mocha 250k
RequireJS 14.7k
Rafael 89.2k
Total !!!!!!k

* To be fair, I've not gzipped these libs

VanillaJS

What is it

Don't use a library, do it yourself

Size

depends

Strengths

  • Typically smaller filesize
  • Can optimize for your specific use-case

Weaknesses

  • No free upgrades or bug-fixes

VanillaJS

Example


var name = document.getElementById('name');
name.innerHTML = 'this is the text';
					

Questions?

@rob_rich

http://robrich.org/