pushState + ajax (fetch) = pjax
A simple, small and modern implementation of pjax
- pjax-api: A full-featured pjax written in TypeScript
- barba.js: A library that provides smooth transition
- jquery-pjax: A jQuery plugin for pjax
- pjax: A standalone pjax
npm install --save-dev little-pjax
import PJAX from "little-pjax";
const pjax = new PJAX("#pjax-root", "a[href]:not[target]");
pjax.addEventListener("loadend", (e) => console.log("finish loading"), false);
PJAX will replace:
document.title
- A container element
- URL
Target anchor elements are selected via the second argument from a container element.
If href
of a target anchor element is not same Origin, it will be ignored.
<script>
in a container element will be loaded after the element is replaced.
The pages visited before are cached inside PJAX.
Cache stores page data for one session. When reloading a page, it gets cleared.
PJAX will NOT work:
- with Shift + click, Ctrl + click, Alt + click
- if a
click
event was prevented before - if the new URL is same with the current one
PJAX does NOT support:
- Multiple container elements
- Other elements in
<head>
such as<meta name="twitter:card">
,<script>
- Inheritance of element's event handlers to the new elements
You have to recall element.addEventListener()
after contentLoaded
or load
event.
You can use the contentLoaded
event to hook to sync <meta name="twitter:card">
.
PJAX < EventTarget
const pjax = new PJAX(container, target);
container: string
= body
A group of selectors of a container element.
target : string
= a[href]:not([target])
A group of selectors of target HTMLAnchorElement
.
Same as EventTarget
. addEventListener
and removeEventListener
.
All events are instances of CustomEvent
and fired from an instance of PJAX.
loadstart -> beforeunload -> unload -> contentLoaded -> loadend
loadstart -> beforeunload -------- (canceled) --------> loadend
Fired when have started loading the next page.
Cancelable.
Fired before fetching new resouces.
When canceled, PJAX will stop loading and will not fire unload
and contentLoaded
.
contentLoadedEvent.detail.url
: string
a URL of the new page.
Fired before replacing a container element.
Fired after replacing a container element and before executing JavaScript.
contentLoadedEvent.detail.document
: Document
Document
of the new page.
You can use it, for example, to sync <meta name="twitter:card">
.
pjax.addEventListener("contentLoaded", (event) => {
const newDocument = event.detail.document;
const oldCard = document.head.querySelector('meta[name="twitter:card"]');
const newCard = newDocument.head.querySelector('meta[name="twitter:card"]');
oldCard.replaceWith(newCard);
});
Fired when have finished all progress.
CC0-1.0