Pjax loads page using ajax & updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving a fast page load.
_But under the hood, it's just ONE http request with a pushState() call._
Obviously, for [browsers that don't support pushState()](http://caniuse.com/#search=pushstate) Pjax fully degrades (yeah, it doesn't do anything at all).
It simply works with all permalinks & can update all parts of the page you
want (including html metas, title, navigation state).
- It's not limited to one container, like jQuery-Pjax is,
- It fully support browser history (back & forward buttons),
- It **will** support keyboard browsing (@todo),
- Automatically fallback to classic navigation for externals pages (thanks to Capitain Obvious help),
- Automatically fallback to classic navigation for internals pages that will not have the appropriated DOM tree,
- You can add pretty cool CSS transitions (animations) very easily.
- It's around 3kb (minified & gzipped).
### Under the hood
- It listen to every clicks on links _you want_ (by default all of them),
- When a internal link hitted, Pjax grabs HTML from your server via ajax,
- Pjax render pages DOM tree (without loading any resources - images, css, js...)
- It check if all defined parts can be replaced:
- if page doesn't suit requirement, classic navigation used,
- if page suits requirement, Pjax does all defined DOM replacements
- Then, it updates the browser's current url using pushState
## Overview
Pjax is fully automatic. You won't need to setup anything on the existing HTML.
You just need to designate some elements on your page that will be replaced when
you navigate your site.
Consider the following page.
```html
<!doctype html>
<html>
<head>
<!-- metas, title, styles, ... -->
</head>
<body>
<header class="my-Header"><nav><!-- a .is-active is in there --></nav></header>
<section class="my-Content">
Sha blah <a href="/blah ">blah</a>.
</section>
<aside class="my-Sidebar">Sidebar stuff</aside>
<footer class="my-Footer"></footer>
<script src="onDomReadystuff.js"></script>
<script><!-- analytics --></script>
</body>
</html>
```
We want Pjax to grab the url `/blah` then replace `.my-Content` with whatever it gets back.
Oh and the `<nav>` (that contains a status marker somewhere) can be updated too (or stay the same, as you wish).
And also the `<aside>` please.
So we want to update `[".my-Header", ".my-Content", ".my-Sidebar"]`, **without reloading styles nor scripts**.
We do this by telling Pjax to listen on `a` tags and use CSS selectors defined above (without forgetting minimal meta):
``` javascript
new Pjax({ selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"] })
```
Now when someone in a Pjax-compatible browser clicks "blah" the content of all selectors will be replaced with the one found in the "blah" content.
_Magic! For real!_ **There is completely no need to do anything on server side!**
## Differences with [jQuery-pjax](https://github.com/defunkt/jquery-pjax)
- No jQuery dependency,
- Not limited to a container,
- No server side requirements,
- Works for CommonJS environment (browserify), AMD (RequireJS) or even globally,
- Allow page transition with CSS animations,
- Can be easily hacked since every method is public (so overridable)
## Installation
You can install pjax from **npm**
```shell
$ npm install pjax
```
Or using **bower**
```shell
$ bower install pjax
```
Pjax can obviously be downloaded directly.
## No dependencies
_There is nothing you need. No jQuery or something._
## Compatibility
Pjax only works with [browsers that support the `history.pushState` API](http://caniuse.com/#search=pushstate).
When the API isn't supported Pjax goes into fallback mode (it just does nothing).
To see if Pjax is actually supported by your browser, use `Pjax.isSupported()`.
## Usage
### `new Pjax()`
Let's talk more about the most basic way to get started:
```js
new Pjax({
elements: "a" // default is "a[href], form[action]"
This will enable Pjax on all links and designate the part to replace using CSS selectors `"title", ".my-Header", ".my-Content", ".my-Sidebar"`.
For some reason, you might want to just target some elements to apply Pjax behavior.
In that case, you can 2 differents things:
- use a custom selector like "a.js-Pjax" or ".js-Pjax a" depending on what you want.
- override `Pjax.prototype.getElements` that just basically `querSelectorAll` the `elements` option. In this function you just need to return a `NodeList`.
// here it's a stupid example since it's the default behavior too
oldEl.outerHTML = newEl.outerHTML
this.onSwitch()
},
".js-Pjax": Pjax.switches.sideBySide
}
})
```
Callbacks are binded to Pjax instance itself to allow you to reuse it (ex: `this.onSwitch()`)
###### Existing switches callback
-`Pjax.switches.outerHTML`: default behavior, replace elements using outerHTML
-`Pjax.switches.innerHTML`: replace elements using innerHTML & copy className too
-`Pjax.switches.sideBySide`: smart replacement that allow you to have both elements in the same parent when you want to use CSS animations. Old elements are removed when all childs have been fully animated ([animationEnd](http://www.w3.org/TR/css3-animations/#animationend) event triggered)
Internaly, this option is used when `popstate` is used (to not pushState again).
You should forget that option.
##### `analytics` (Function, default to a function that push `_gaq` `trackPageview` or send `ga` `pageview`
Function that allow you to add behavior for analytics. By default it try to track
a pageview with Google Analytics.
It's called every time a page is switched, even for history buttons.
##### `scrollTo` (Integer, default to 0)
Value (in px) to scrollTo when a page is switched.
##### `debug` (Boolean, default to false)
Enable verbose mode & doesn't use fallback when there is an error.
Useful to debug page layout differences.
#### Extend Pjax
Pjax prototype & utilities methods can be used & changed so you can patch or hack
Pjax behavior, as you wish.
Here is a summary of functions:
-`Pjax.isSupported` (`function()`): return wheter or not the browser handle pushState correctly
-`Pjax.on` (`function(els, events, listener, useCapture)`): addEventListener, that handles NodeList & supports space separated event name
-`Pjax.off` (`function(els, events, listener, useCapture)`): removeEventListener, that handles NodeList & supports space separated event name
-`Pjax.trigger` (`function(els, events)`): fireEvent, that handles NodeList & supports space separated event name
-`Pjax.clone` (`function(obj)`): clone object
-`Pjax.executeScripts` (`function(el)`): execute scripts that are inside an element (script src or inline scripts through `Pjax.evalScript`)
-`Pjax.evalScript` (`function(el)`): execute inline script. Don't execute a script if it contains `document.write`.
-`Pjax.prototype.log` (`function()`): console.log function that is enable/disabled by `debug` option
-`Pjax.prototype.getElements` (`function(el)`): retrieve elements to attach Pjax behavior
-`Pjax.prototype.parseDOM` (`function(el)`): parse DOM to attach behavior using `Pjax.prototype.getElements` & `Pjax.prototype.attachLink`
-`Pjax.prototype.attachLink` (`function(el)`): attach Pjax behavior to a link
-`Pjax.prototype.forEachSelectors` (`function(cb, context, DOMcontext)`): call a function for each selectors defined
-`Pjax.prototype.switchSelectors` (`function(selectors, fromEl, toEl, options)`): loop on selectors to switch elements
-`Pjax.prototype.latestChance` (`function(href)`): when everything is fucked up, it's our only hope (just call `window.location = href`)
-`Pjax.prototype.onSwitch` (`function()`): callback triggered when elements are switched, for now it's just trigger a window resize event (lots of lib are listening to this event to draw stuff)
-`Pjax.prototype.loadContent` (`function(html, options)`): switch elements for each selectors
-`Pjax.prototype.doRequest` (`function(location, callback)`): make the ajax request to grab page from the server
-`Pjax.prototype.loadUrl` (`function(href, options)`): do the ajax request, handle html results & eventually handle browser history, analytics & scroll.
### Events
Pjax fires a number of events regardless of how its invoked.
All events are fired from the _document_, not the link was clicked.
#### Ajax related events
*`pjax:send` - Fired after the Pjax request begins.
*`pjax:complete` - Fired after the Pjax request finishes.
*`pjax:success` - Fired after the Pjax request succeeds.
*`pjax:error` - Fired after the Pjax request fails. Returning false will prevent the the fallback redirect.
`send` and `complete` are a good pair of events to use if you are implementing a loading indicator (eg: [topbar](http://buunguyen.github.io/topbar/))
```js
$(document).on('pjax:send', topbar.show)
$(document).on('pjax:complete', topbar.hide)
```
#### Note about DOM ready state
Most of the time, you have code attached & related to the current DOM, that you only execute when page/dom is ready.
Since Pjax doesn't magically rexecute you previous code each time you load a page, you need to make a simple thing to rexecute appropriate code: