Using Pjax to make page navigation user friendly



Understanding this, requires a little knowledge of Javascript, Jquery and Ajax. Pjax is nothing more but an extension of Ajax with the support of push state.

First of let us understand what is page navigation, when ever user encounters a page link which may be a different page in the same site using , he is redirected to that page. It basically means content of the current page are removed and that page are loaded along with all the javacript and css, which may not be different from current page, (it may not be so if we take browser caching into consideration).

But again the point here is that using pjax this complete action can be avoided and only the required content which changes, could be loaded(which is exactly what happens in ajax), but with the difference that url will also change, and user understands this a different page, and he can use back and forward button as if the page has actually navigated.

You can see the complete working demo here.
Now how do we do it. Very basic and simplest method :
  • Include Jquery and Pjax file in your script files.
  • you can use normal href links, but in javascript you have to use jquery. eg.


    $('a').click(function(e){
     window.pjax.fetch($(this).attr('href'),'body#id');
    // body#id is the body element id where the content should be fetched to
    });



Also Note that the body id for pjax needs to be present in both the pages i.e. the current page, and the new page. Basically behind the scene the content of body#id from new page will replace content of body#id in the current page. That's it. Happy Pjaxing!!

No comments: