Effective jQuery

Patterns for maintainability and performance

Jörn Zaefferer
bassistance.de / @bassistance

Quiz Time

What is the most popular jQuery version on the jQuery CDN?

  1. jquery-1.4.2.min.js
  2. jquery-1.7.2.min.js
  3. jquery-1.9.1.min.js
  4. jquery-1.10.2.min.js

1. Write code like you spend fuel

Adapted from Doug Neiner's Contextual jQuery series

Initializing JavaScript

Lazy init autocomplete demo

Lazy init an autocomplete widgets

Lazy init many autocomplete widgets

Lazy init datepickers

Lazy init datepicker demo

Lazy init dialogs

Lazy init dialog demo

Lazy init form validation

Lazy init form validation demo

heise.de two clicks for more privacy

2. Write code like you don't know the road

Someone is going to mess up the HTML

Flexible draggable handle demo

Traversing example

Flexible over brittle traversing methods

Use flexible methods!

  • prevAll > prev
  • nextAll > next
  • closest > parent
  • find > children

Flexible over brittle traversing example

Flexible over brittle traversing example

Flexible over brittle traversing example

Flexible over brittle selectors

Use flexible selectors!

3. Write code like you avoid traffic jams

Why does this take >2 seconds?!

Use profiler to find out!

Runs in <60ms!

4. Combine tools like you'd park and ride

Custom tooltip demo

Custom tooltip with CSS transitions

Custom tooltip with CSS transitions

Custom tooltip with using transit plugin

CSS transitions: declarative or not?

Matter of preference, control and fallbacks

Fallback to jQuery animations

For supported properties

Animated page scroll demo

Animated page scroll

Animated page scroll

5. Customize widgets like customizing a car

Flick theme, original CSS

Flick theme, custom CSS

Options for CSS customization

  • ThemeRoller
  • Overrides
  • Use structure.css, write theme from scratch
  • Everything from scratch

Quiz Time Answer

What is the most popular jQuery version on the jQuery CDN?

  1. jquery-1.9.1.min.js, #1, 1650m hits, 55 TB
  2. jquery-1.7.2.min.js, #2, 1260m hits, 35 TB
  3. jquery-1.10.2.min.js, #5, 990m hits, 32 TB
  4. jquery-1.4.2.min.js, #15, 290m hits, 5 TB

1. Write code like you spend fuel

plan ahead, spend as necessary, keep a reserve

2. Write code like you don't know the road

be flexible, avoid brittle methods and selectors

3. Write code like you avoid traffic jams

avoid JavaScript rush hours, use a profiler when you run into unexpected bottlenecks

4. Combine tools like you'd park and ride

make use of CSS transitions, combine with jQuery

5. Customize widgets like customizing a car

don't build widgets from scratch when you can adjust them to your needs