skerbis / pjax

Vanilla JS implementation of jQuery pjax plugin

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

pjax = pushState + ajax

This is a vanilla version of the popular PJAX plugin for jQuery by Chris Wanstrath.

Installation

pjax depends axios for making HTTP requests.

Usage

Server-side configuration

Ideally, your server should detect pjax requests by looking at the special X-PJAX HTTP header, and render only the HTML meant to replace the contents of the container element (#pjax-container in our example) without the rest of the page layout.

pjax options

key default description
timeout 650 ajax timeout in milliseconds after which a full refresh is forced
push true use [pushState][] to add a browser history entry upon navigation
replace false replace URL without adding browser history entry
maxCacheLength 20 maximum cache size for previous container contents
version a string or function returning the current pjax version
scrollTo 0 vertical position to scroll to after navigation. To avoid changing scroll position, pass false.
type "GET" see axios
container CSS selector for the element where content should be replaced
url link.href a string or function that returns the URL for the ajax request
target link eventually the relatedTarget value for pjax events
fragment CSS selector for the fragment to extract from ajax response

You can change the defaults globally by writing to the pjax.defaults object:

pjax.defaults.timeout = 1200

pjax.click

This example uses the current click context to set an ancestor element as the container:

if (pjax.supported()) {
  document.querySelectorAll('a[data-pjax]').forEach(link => {
    link.addEventListener('click', e => {
      var container = e.currentTarget.closest('[data-pjax-container]');
      var containerSelector = '#' + container.id;
      
      pjax.lick(e, {container: containerSelector});
    });
  });
}

pjax.submit

Submits a form via pjax.

document.querySelectorAll('form[data-pjax]').forEach(form => {
  form.addEventListener('submit', e => {
    pjax.submit(e, 'pjax-container');
  });
});

pjax.reload

Initiates a request for the current URL to the server using pjax mechanism and replaces the container with the response. Does not add a browser history entry.

pjax.reload('#pjax-container', options)

pjax

Manual pjax invocation. Used mainly when you want to start a pjax request in a handler that didn't originate from a click. If you can get access to a click event, consider pjax.click(event) instead.

function applyFilters() {
  var url = urlForFilters()
  pjax({url: url, container: '#pjax-container'})
}

Events

All pjax events except pjax:click & pjax:clicked are fired from the pjax container element.

event cancel arguments notes
event lifecycle upon following a pjaxed link
pjax:click ✔︎ options fires from a link that got activated; cancel to prevent pjax
pjax:beforeSend ✔︎ axios, options can set XHR headers
pjax:start options
pjax:send options
pjax:clicked options fires after pjax has started from a link that got clicked
pjax:beforeReplace contents, options before replacing HTML with content loaded from the server
pjax:success data, status, response, options after replacing HTML content loaded from the server
pjax:timeout ✔︎ axios, options fires after options.timeout; will hard refresh unless canceled
pjax:error ✔︎ response, textStatus, error, options on ajax error; will hard refresh unless canceled
pjax:complete response, textStatus, options always fires after ajax, regardless of result
pjax:end response, options
event lifecycle on browser Back/Forward navigation
pjax:popstate event direction property: "back"/"forward"
pjax:start null, options before replacing content
pjax:beforeReplace contents, options right before replacing HTML with content from cache
pjax:end null, options after replacing content

pjax:send & pjax:complete are a good pair of events to use if you are implementing a loading indicator. They'll only be triggered if an actual XHR request is made, not if the content is loaded from cache:

document.addEventListener('pjax:send', () => {
  document.getElementById('loading').style.display = 'block';
});
document.addEventListener('pjax:complete', () => {
  document.getElementById('loading').style.display = 'none';
});

An example of canceling a pjax:timeout event would be to disable the fallback timeout behavior if a spinner is being shown:

document.addEventListener('pjax:timeout', e => {
  // Prevent default timeout redirection behavior
  e.preventDefault()
})

About

Vanilla JS implementation of jQuery pjax plugin


Languages

Language:JavaScript 100.0%