HTML History & You

And how to keep your hair
when working with it

@lukekarrys
JavaScript developer @meltmedia

I helped make this!

Why?

  • Reduce loading time
  • Reduce resource consumption
  • Do it the right way

How?

  • Feature detect
return !!(window.history && history.pushState);
  • Push it real good
history.pushState(
  {stateData: "newPage"},
  "New Page Title",
  "newPage.html"
);
  • Make it pop
window.onpopstate = function() { /* Magic... */ };

Browser support

Beware of partial support!

Problems

  • Do you want to hashbang?
  • Buggy browser implementations
  • Event binding (and rebinding, and rebinding...)
  • The easy way isn't the best way
  • There will be complications (and blood)

I Can Haz Solutions?

  • Think of the user!
  • Use a (well tested) library
  • Make it automatic
  • Don't do it all with JS
  • Plan, plan, plan

To hashbang or not to hashbang?

  • Is it a site? Or an app?
  • JavaScript disabled users
  • Search engine crawling
Twitter with no JS

Spec? What spec?

Event binding

  • Delegate as much as possible
  • $('#content').delegate('a.callout', 'click', fn);
  • When you can't, use context specific JS
  • $('.new-el', newContext).yourSpecialJS();
  • I wrote a plugin to help!
  • $(function() {
      $('p', this).each(function() {
        $(this).css('background', 'red');
      });
    }, true);
    

You can do it all with JS
(but don't!)

// Too easy...
$('a').click(function() {
  $('#content).empty().load(this.href + ' #content');
  return false;
});

Serve only content that you will display

  • Reduce request size
  • Browser won't request assets you'll never see
  • Less client side parsing with JavaScript

It could get messy

  • Architect every feature with history API in mind
  • Don't get too complicated (unless you want to)
  • Blacklist/whitelist URLs