little-pjax v0.4.0
little pjax
pushState + ajax (fetch) = pjax
A simple, small and modern implementation of pjax
Prior arts
- 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
Install
npm install --save-dev little-pjaxUsage
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
clickevent 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">.
API
PJAX()
PJAX < EventTarget
const pjax = new PJAX(container, target);Options
container: string = body\
A group of selectors of a container element.
target : string = a[href]:not([target])\
A group of selectors of target HTMLAnchorElement.
Methods
Same as EventTarget. addEventListener and removeEventListener.
Events
All events are instances of CustomEvent and fired from an instance of PJAX.
loadstart -> beforeunload -> unload -> contentLoaded -> loadend
loadstart -> beforeunload -------- (canceled) --------> loadendloadstart
Fired when have started loading the next page.
beforeunload
Cancelable.
Fired before fetching new resouces.
When canceled, PJAX will stop loading and will not fire unload and contentLoaded.
Properties
contentLoadedEvent.detail.url: string\
a URL of the new page.
unload
Fired before replacing a container element.
contentLoaded
Fired after replacing a container element and before executing JavaScript.
Properties
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);
});loadend
Fired when have finished all progress.
LICENSE
CC0-1.0