Personal Projects >

PJAX

What is PJAX?

In the never ending quest to create fast pages for users, I came across PJAX by complete accident. After reading up about it, I decided to put it into a project of mine which was some web software written in laravel.

This is the version of PJAX that I decided to use, mostly because it was the first one that I found, and I also used a middleware for laravel inspired by this one

It was a little rough to start with, since I had quite a few js files to change as a result, but in the end I made a mini onload function which fired events on page load and pjax send, and in the version I made it comes built in (and much more improved)


How it works

I think the most succinct (albeit technical) definition of what PJAX does is as follows:

PJAX utilizes the browser pushstate and history in order to replace the content of a container on the page with that of the next request via ajax

What this means, is that the initial load will load up all the general assets, and some HTML elements only once, thereby decreasing the amount of requests to page to typically only one (as only the content of the page is replaced). It is also possible to create some animations and add loaders to pages very simply, but I didn’t put that into my version


Building my own version of PJAX

As a result of much more research into how PJAX works, I decided that I wanted to make my own version, without using any dependencies and making it extendible

I started with this current site, and seeing how to make it all work. After much testing and many, many different versions of it, I ended up with a version that I was happy with, and needed no server configuration to work as well, so making it ideal for static sites!

This is what I came up with, and can be slotted into pretty much any website and it should just work (this is a basic version of pjax, so it doesn’t handle things like form submits). I also wanted to make it into an ES6 class after writing it in ES5 because I just prefered the syntax and it can be more reusable than the initial version (and maintainable! I added a bunch of documentation to it)

One of the bigger snags I came across, is that if there is a script tag within the bit that PJAX replaces, it doesn’t actually get executed on a new pjax request because how the escaping works in replacing the HTML. In order to get the scripts to execute, I read up a bit on the jQuery docs and found this useful function and implemented a slightly changed version of it into my PJAX script