[screenflow start, manually, select projector!]
Have you heard about the car that was made entirely out of wood?
Yeah, it wooden move / or something about food for thought / Olá! How are you today?
I've got these [hold up five fingers] five patterns I want to talk about today. Each should help you use jQuery more effectively.
I selected these five from my work on jQuery UI and QUnit and other projects. To make them sticky, I came up with a few car and driving related analogies.
First, I have a quiz for you!

Effective jQuery

Patterns for maintainability and performance

What is the most popular jQuery version on the jQuery CDN?
a, 1.4.2, b, 1.7.2, c, 1.9.1, d, 1.10.2?
who thinks its a? [wait] b? [wait] c? [wait] d? [wait] alright, most hands are for X
I will give the answer later, for now, let's look at the first pattern!

Quiz Time

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

jquery-1.4.2.min.js

jquery-1.7.2.min.js

jquery-1.9.1.min.js

jquery-1.10.2.min.js

1. pattern: Write code like you spend fuel
I adapted this from Doug Neiner's "write code like you spend money".
When low on fuel, we don't drive as fast as possible to get to the next gas station
But when the tank is full and we're in a hurry, we can drive a little faster
How does this apply to JavaScript?
Let me show show you...

1. Write code like you spend fuel

Adapted from Doug Neiner's Contextual jQuery series

In JavaScript we have a choice when to run code
Before anything happens; on document ready; on window load;
Or, what I usually recommend: the one down here, commented as "cool place"
If you've got too much code running too early, it will slow down loading of the page
How can we address that?
Let's look at a few examples

Initializing JavaScript

In thist first one, there's several inputs with the autocomplete widget attached
I click the first input, start typing
You see the menu showing suggestions
Each of those widgets is initialized just in time, not on page load!
With a lot of elements this is important - this table here could have hundreds of rows.
How does the just in time initialization work?

Lazy init autocomplete demo

This first input uses lazy initialization, with jQuery's .one() method
The event handler will run once, initialize the autocomplete, then remove itself

Lazy init an autocomplete widgets

This gets more interesting when dealing with a lot of inputs, like a big table
Using event delegation needs only a single event handler on their common container
The selector includes a class that the event handler removes, that way each input is initialized only once, just in time

Lazy init many autocomplete widgets

This works for datepicker as well
Just emulate the default "on focus" behaviour by calling the show method
otherwise same approach as for autocomplete

Lazy init datepickers

quick demo of datepicker, no surprises here either

Lazy init datepicker demo

dialog's usually have a trigger, so we can make use of that
Auto opens on init, manually open later

Lazy init dialogs

Again, no surprise here
[click the link to open the dialog]

Lazy init dialog demo

Event delegation can also be used for form validation
Even works for clicks on the submit button

Lazy init form validation

[Click submit button]
See, submit event is triggered after focusin
In addition to these demos, I want to show you an example of lazy initialization in the wild

Lazy init form validation demo

This is from a german IT news site
Instead of loading "social" widgets on page load
They introduced an extra click. Good for performance AND privacy.
Options to always load some or all of them. [point at the checkboxes in popup]
That concludes the first pattern, "Write code like you spend fuel"
Coming up next:

heise.de two clicks for more privacy

2. pattern: Write code like you don't know the road
This one is about the interaction between JavaScript, HTML and CSS
Its common to change markup to allow changes in CSS.
But this can break brittle JS code.

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

Someone is going to mess up the HTML

This demo has an element that can be dragged by its handle
The handle shows up on hover
I can drag around with the mouse
This is just a simple demo. Imagine what would happen when one change request after the other requires changing the markup of this element.
It would probably break our underlying JavaScript. Let's check the code!

Flexible draggable handle demo

At the top is the markup, below the JS applied to that
This uses the children method to find the handle container
This would break when the handle ends up wrapped in another element
Instead of the children() method, we can use the find() method to avoid that
Doug Neiner called these 'flexible' and 'brittle' methods

Traversing example

You should use flexible traversing methods
These are less likely to break when making changes
For the given example, its really easy to apply:

Flexible over brittle traversing methods

Use flexible methods!

prevAll > prev

nextAll > next

closest > parent

find > children

Just replace children() with find()
If we were to change the markup now, the JS would continue to work without changes

Flexible over brittle traversing example

What does this?
Matches if the next sibling is a div
Would break if any other element is inserted inbetween.

Flexible over brittle traversing example

Here if looks through next siblings until it finds a div and matches only that.
Allows you to insert other siblings without breaking this traversal.

Flexible over brittle traversing example

The same applies to selectors, for example in the context of event delegation.
Pick the more flexible selector here, since clicks don't happen often.
Here's its better to match clicks based on the href, instead of relying on a specific class
So, write code like you don't know the road. Use flexible methods and selectors.
Which also applies to the next pattern:

Flexible over brittle selectors

Use flexible selectors!

3. pattern: Write code like you avoid traffic jams
Traffic jams are like performance bottlenecks
Always thinking about traffic jams is a waste of time
But we can avoid well known rush hours!
When it comes to jQuery, there's a few traffic jams we can look out for
Usually having thousands of elements on a page will cause jams
Doing lots of processing in mousemove events is also a bad idea

3. Write code like you avoid traffic jams

Occasionally its less obvious.
Here's some jQuery code that creates a list of items, which looks pretty innocent.
It sets text and data for each list item,
Then each item is added to a jQuery object, which is then added to the page
Just one DOM operation, so why does it take more then two seconds for just 400 items?
This is a good opportunity to use a profiler

Why does this take >2 seconds?!

When I ran into this problem, I could already tell which part of my code was responsible
It looked something like this
I couldn't tell why it was so slow, so I added these profile calls around it [activate highlight]
I then ran the code again and looked at the profile that Chrome created

Use profiler to find out!

here's a screenshot of Chrome's flame graph of a profile
hovering elements will show details
here are the details for the add method
total time is high, self time is low
we can see in the graph that add is calling uniqueSort...
which has pretty much the same total time, but lots more self time
so probably most time is spent here
When digging into this, I learned that this isn't a new issue, has actually been around for a long time
Other methods had this problem as well, got fixed back around jQuery 1.5, including these graphs in the release blog post
here the 1.4.4 performance in blue, 1.5 in green
for the children method
next and prev also got a lot faster
children, next and prev used to call uniqueSort, which sorts selected elements in DOM order
the add() method is slow, since it still sorts, but luckily its really easy to work around that...
Here's pretty much the same code, replacing the jQuery object with a plain array
Takes less then 60ms, so much much faster
Again: Write code like you avoid traffic jams!
In this case, the answer could be found in JavaScript
In other cases, we have to look a little further
Which brings us to:

Runs in <60ms!

4. pattern: Combine tools like you would park and ride
jQuery pioneered a lot of new APIs
Most are now available in the browser without libraries, via JavaScript, like querySelectorAll or classList.
One particular new API got exposed via CSS: Transitions
Since jQuery animations tend to be very slow on mobile devices, CSS transitions are quite valuable there
They don't replace jQuery, but combining both is very poweful

4. Combine tools like you'd park and ride

let's start with a demo
this page implements a custom tooltip on anchors
[slowly hover the elements]
Let's look at the options for implementing these fade animations

Custom tooltip demo

here's the CSS for a custom tooltip using transitions for the fade effect
a lot of this is just general styling
[activate highlight]
relevant for the transition is opacity and transition
let's look at the javascript for that

Custom tooltip with CSS transitions

Implementing the tooltip in JavaScript involves creating a tooltip element
Positioning that in the right place, setting the text and removing the title attribute
Once all that is done, the "tooltip-visible" class is added.
All that happens on mouseenter; on mouseleave, the title is restored and the class is removed.
This works, but we can also control the transition from JavaScript