So I have been working on trying out PJAX. PJAX is a technique where you can update a certain part of a page WITH support to change the browser URL bar when the request finishes.
So basically, it's AJAX + pushState.
You can easily get started by using the jQuery PJAX plugin if you are using jQuery: https://github.com/defunkt/jquery-pjax
Add the code to your Rails project and you are good to go. Here is an example of a Dutch website I am working on: http://volgendboek.nl.
In my application.js I make sure all my <a> tags will be loaded using PJAX:
This single line causes every link to be loaded with PJAX. It will first load the page and replaces the element with id="main" with the content loaded from the PJAX request.
Then, it will update the browser URL bar to reflect the new URL.
Here is a shortened snippet of my application.html.erb layout:
All new pages will just render everything with the layout and put the view inside the <div id="main"></div> tag. When loading the page with PJAX it will put the returned html into this div.
This is the html a view renders:
<title>Serie: <%= @series.title %></title> <div class="container"> <h1><%= @series.title %></h1> <div class="books"> <%= render @series.books %> </div> </div>
When making your view, you need to think of two things:
First, make sure to include a <title> tag in your view. Since jQuery PJAX will also update your browser's title bar. Which is awesome!
Second, it's important to wrap all the content you would like to load in some kind of container element. I use <div class="container"> here but you can use any element as container. This is important because jQuery PJAX will look for a container element in the response to load into the page.
There's also a thing you need to do in your controller. You need to make sure your layout does not get rendered with a PJAX request.
So, for instance in my BooksController I have:
class BooksController < ApplicationController def show @book = Book.find(params[:id]) @series = @book.series @offset = params[:offset] if request.xhr? render :layout => false end end end
I am using request.xhr? to check if it's a PJAX request since every PJAX request is an AJAX request.
You can use the https://github.com/rails/pjax_rails plugin, which adds a helper to do these kind of things so you can write:
if pjax_request? render :layout => false end
Take a look at that plugin. It has some nice features for using PJAX in Rails.