the ramblings of a programmer

Rolling your own PJAX implementation with History.js

If you were like me, at some point you read somewhere about this cool new thing called PJAX. Essentially, instead of issuing normal HTTP requests when navigating a site, links are fetched and loaded via AJAX to avoid full page refreshes. The site feels much more responsive. This isn’t without it’s quirks however.

My issue with PJAX largely revolved around the inability to implement animations. First and foremost, the provided hooks weren’t sufficient. It was possible to rig something up with CSS and class swapping, but not only did that feel gross it often broke down as soon as the back button entered the picture. Although PJAX felt slightly faster, without animations it was just as jarring as a full page refresh and so I didn’t see a point.

As I was working on the redesign of this site, I decided to take another look to see what had changed. Unfortunately I discovered not much had. However, instead of moving on this time I decided to take a quick look for any alternative solutions. I pleasantly discovered History.js.

After a little bit of fiddling, I had quickly rolled my own PJAX implementation powered by History.js. Thinking there may be a few people out there that are in the same spot I was, I figured I’d post a quick write up.

First we start off with your usual boilerplate.

1
2
3
4
5

(function($){var$document=$(document);// our code ...})(jQuery);

The next thing we need to do, and I wish more JavaScript developers kept graceful degradation in mind, is check whether or not the browser supports the HTML5 history API. History.js makes this easy for us.

1
2
3

if(!History.enabled){returnfalse;}

Now if we run into an unsupported browser our site doesn’t cease to function. As an added bonus, there will be one less site out there that’s shoving some snarky message in the user’s face about how they need to upgrade to a real browser so they can experience the greatness that is four different versions of jQuery being used to style some text.

Moving on, before we get to implementing anything, we have a bit more setup to do.

The first thing we’re doing here is caching a value that we’ll be using later. After that we’re defining a custom jQuery pseudo selector so we can avoid littering our markup with data-* attributes. Lastly, we’re defining a few helper functions to make our code easier to work with.

Although these helper functions are fairly straightforward, I’ll quickly run through them. The first, find_all, simply grabs all occurrences of selector in the supplied chunk of HTML. Next, parse_all abstracts the process of turning a chunk of HTML into a jQuery object.

The last helper function is parse_response and it’s a bit more significant compared to the rest. This is where we’re parsing the AJAX response for the title and the chunk of the page that we’re trying to load. Line 24 is worth singling out as you’re likely going to want to change it to work with your site.

Depending on your use case you may wish to alter the above, but for basic usage it’s likely sufficient. All we’re doing here is changing our internal links to use the HTML5 history API.

The key thing here is actually the selector where we’re using our custom pseudo selector from earlier. A link is considered internal if it’s on the same domain and ends with either / or .html. Again, depending on your use case, you may want to change that.

// This is the event that's triggered by the HTML5 history API.$(window).on('statechange',function(){varurl=History.getState().url,rel=url.replace(root,'/');// Here we're making our AJAX call.$.get(rel).done(function(date){varresponse=parse_response(date);// First we need to check if the chunk we were looking for was found// in the response. If it wasn't we reject the link.if(!response.$content.length){document.location.href=url;returnfalse;}// This is our target container.var$content=$('#content');// Here we're updating the page title if one was found in the response.if(response.title.length){$('title').last().html(response.title);}// Now we're loading the response.$content.slideUp(500).promise().done(function(){$content.html(response.$content).slideDown(500);});// If the AJAX request failed, we're again rejecting the link.}).fail(function(){document.location.href=url;returnfalse;});});

I’ve gone ahead and annotated most of what’s going on in the comments. The only things I’ll bring up specifically are lines 20 and 28 to 35. As before, you’re likely going to want to change the selector on line 20. You’re also likely going to want to change how the response is loaded which would be lines 28 to 35.

And there we have it. A simple, straightforward PJAX implementation that doesn’t restrict us when it comes to how we want to handle loading our PJAX responses. It’s by no means perfect or without flaws, but it’s solid enough for basic usage and easily extensible for more complicated use cases.

about

My name is Andrew Fricke, for the most part I'm a web developer, and this is where I ramble. This site is powered by a static site generator I wrote called mynt and there's also a feed. If you want to get in touch, you can find me on GitHub, Twitter, and I also hang out on IRC—Anomareh@freenode.