0.6.6 • Published 7 months ago

pjax.js v0.6.6

Weekly downloads
5
License
MIT
Repository
github
Last release
7 months ago

Automatic Pjax

The Pjax.js is a jQuery plugin script that uses ajax, pushState and automatically detects links and forms, for configure page you need use id="pjax-container" in all pages, example:

<div id="pjax-container">
    ...
</div>

Pjax load all content from pages, but uses only contents from first element using pjax-container, if you don't need the Pjax in a spefic link or form then use data-pjax-ignore attribute, example:

<p>
    Hello world!
    Example <a data-pjax-ignore href="/page.html">page</a>.
</p>

Setup

Include lib

<link rel="stylesheet" type="text/css" href="pjax.min.css" data-pjax-resource="true">
<script src="pjax.min.js"></script>

Or use CDN:

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pjax.js@0.6/pjax.min.css" data-pjax-resource="true">
<script src="https://cdn.jsdelivr.net/npm/pjax.js@0.6/pjax.min.js"></script>

Note: CSS is optional, you can create your own loader or customize the following structure using CSS (the structure is generated by Pjax.js):

<div class="pjax-loader pjax-start pjax-inload pjax-end pjax-hide">
    <div class="pjax-progress"></div>
</div>

Import:

const Pjax = require('pjax.js');

...

ESM/ES6 import:

import Pjax from 'pjax.js';

...

RequireJS:

requirejs(['folder/foo/bar/pjax'], function (Pjax) {
    ...
});

Support

The pjax.js support links, forms with method GET, forms with method POST and support files and multiple files (<input type="file" multiple>).

Requirements:

  • DOMParser or document.implementation
  • pushState, replaceState and popstate (DOM History manipulation)
  • FormData (XMLHttpRequest Level 2) - if need upload files using PJAX (enctype="multipart/form-data")

Tested in:

  • Internet Explorer 10
  • Firefox
  • Google Chrome
  • iOS 10
  • Android 2.3+

Usage

For use:

Pjax.start();

Pjax API

MethodDescription
Pjax.supportedReturn true if support this lib, otherwise return false
Pjax.remove();Remove PJAX requests and events
Pjax.on(event, function (...) {...});Define an event
Pjax.off(event, function (...) {...});Remove an event
Pjax.request(url[, config])Request using script

Pjax.request() method

config param is optional, you can define like this:

Pjax.request("/foo/bar", {
    method: "POST",
    replace: true,
    data: "foo=1&bar=2&baz=3"
});

Uploading file:

const formdata = new FormData;
const blob = new Blob(["Hello World!"], {
  type: "text/plain"
});

formdata.append("file", blob, "hello.txt");

Pjax.request("/foo/bar", {
    method: "POST",
    replace: true,
    data: formdata
});

Details for use data::

Propertytypedefaultdescription
replace:boolfalseSets the history state mode, if you set it to false (or omitted) it will use history.pushState(), but if you set it to true it will use history.replaceState().
method:stringGETDefine HTTP method
data:boolfalseTo send data in the request, you can use String or FormData

Pjax Events

ExampleDescription
Pjax.on("initiate", function (url, config) {...});Trigged when clicked in a link or submit a form or execute Pjax.request() method
Pjax.on("done", function (url, status) {...});Trigged when page loaded, status return HTTP code
Pjax.on("fail", function (url, status) {...});Trigged when page failed to load, status return HTTP code
Pjax.on("then", function (url) {...});Executes every time a request is completed, even if it fails or success
Pjax.on("history", function (url, stateData) {...});Executes every use back or forward
Pjax.on("handler", function (data, config, callbackDone, callbackFail) {...});Create your owner response to Pjax.js request
Pjax.on("dom", function (url, newdocument) {...});Allows you to manipulate an element change manually, for example you can create transitions or change newdocument

Tip: You can use Pjax.on("dom", ...); for remove events in DOM

Pjax configs

Propertytypedefaultdescription
containers:array[ "#pjax-container" ]Informs which elements to update on the page
updatecurrent:boolfalseIf true request same url in used by current page is executed history.replaceState, otherwise nothing will be executed
updatehead:booltrueThe "pjax.js" has an intelligent update system that helps avoid the "blink" effect, because instead of updating everything it only updates what has been changed, however if you are sure that nothing will change as you page, you can set it to false, the only one that will continue to be updated will be the <title> tag
insertion:stringundefinedSupport values append and prepend, if omitted it will replace the content
scrollLeft:number0After loading a page via PJAX you can define where scrollLeft should scroll. Set -1 to disable autoscroll in x-cord
scrollTop:number0After loading a page via PJAX you can define where scrollTop should scroll. Set -1 to disable autoscroll in y-cord
loader:booltrueAdds the native Pjax loader, if you want to create a loader of your own, set it to false
nocache:boolfalsePrevent cache
proxy:string""Set Web Proxy
formSelector:stringform:not([data-pjax-ignore]):not([action^='javascript:'])Set form selector, set empty for prevent forms uses Pjax
linkSelector:stringa:not([data-pjax-ignore]):not([href^='#']):not([href^='javascript:'])Set form selector, set empty for prevent links uses Pjax
headers:objectAdds custom headers, eg.: { "foo": "bar", "test": "baz" }

PJAX with HTML5 data attribute

If need overwrite properties for specific link or form you can config using HTML attributes:

Propertyequivalentexampledescription
data-pjax-containerscontainers:<a href="..." data-pjax-containers="[ &quot;#foo&quot;, &quot;#bar&quot;, &quot;#baz&quot; ]"Adjusts the containers when the request comes from a specific form or link
data-pjax-updateheadupdatehead:<a href="..." data-pjax-updatehead="false"Allow/Disallow head tag update when the request comes from a specific form or link
data-pjax-insertioninsertion<a href="..." data-pjax-insertion="append"Append or prepend data to the containers instead of updating
data-pjax-scroll-leftscrollLeft:<form action="..." data-pjax-scroll-left="10"custom scroll-left to specific form or link
data-pjax-scroll-topscrollTop:<form action="..." data-pjax-scroll-top="-1"custom scroll-top to specific form or link
data-pjax-loaderloader:<a href="..." data-pjax-loader="false"Allow/Disallow loader animate to specific form or link
data-pjax-done-<a href="..." data-pjax-done="console.log('success', this);"Custom "done" event to specific form or link
data-pjax-fail-<a href="..." data-pjax-fail="console.log('error', this);"Custom "error" event to specific form or link
data-pjax-ignore-<a href="..." data-pjax-ignore="true">Normal navigation to specific form or link
data-pjax-resource-<link href="..." data-pjax-resource="true">Prevent remove element after update DOM (for now it only works in the <head>)

For change configs use like this:

Pjax.start({
    containers: [ "#my-container" ], //Change container element
    scrollLeft: -1, //Disable autoscroll
    scrollTop: -1 //Disable autoscroll
});

Update two elements (or more)

You can change the element you want to update or even add more elements, eg.:

<div id="navbar">
    ...
</div>
<div id="my-container">
    ...
</div>
<script>
Pjax.start({
    containers: [ "#navbar", "#my-container" ] //Change containers element
});
</script>

You can change configs in initiate event, example:

<div id="pjax-container">
    <div id="filter">
        <form>
            ...
        </form>
    </div>
    <div id="search-container">
        ...
    </div>
</div>
<script>
Pjax.start();

Pjax.on("initiate", function (url, configs) {
    if (url.indexOf("/search/") === 0 && window.location.href.indexOf("/search/") === 0) {
        configs.containers = [ "#search-container" ];
    }
});
</script>

If you are on a product search page and are doing a new search instead of updating the entire container will only update the element where the products are, other pages will continue to update the entire container.

Pjax in server-side

It is possible to detect if the request came from the PJAX using the request headers:

HeaderDescription
X-PJAXIndicates that the page was requested via PJAX
X-PJAX-ContainerInforms the container selectors used

Example using PHP:

if (isset($_SERVER['HTTP_X_PJAX'])) {
    echo 'You using pjax';
}

Redirect using PJAX

You can use HTTP response header X-PJAX-URL in back-end for force Pjax.js redirects, example:

header('X-PJAX-URL: /new-page.html');

...

Change or add container using PJAX

You can use HTTP response header X-PJAX-URL in back-end for force Pjax.js redirects, example:

if (isset($_SERVER['HTTP_X_PJAX'])) {
    header('X-PJAX-Container: #foo,#bar');

    echo '<div id="foo"> ... </div>';

    echo '<div id="bar"> ... </div>';
}

Custom loader with Pjax

You can custom CSS, example change color and size, put in new CSS file or <style> tag:

.pjax-loader .pjax-progress {
    height: 6px;
    background-color: blue;
}

If you need custom "more", first remove default loader:

Pjax.start({
    loader: false
});

And after use initiate and then events:

Pjax.on("initiate", function () {
    $(".my-custom-loader").css("display", "block");
});

Pjax.on("then", function () {
    $(".my-custom-loader").css("display", "none");
});

HTML:

<div class="my-custom-loader">
    <img src="loader.gif">
</div>

Pjax handler response

For create a custom responses for Pjax you can use handler event, example:

Pjax.start({
    updatehead: false //Prevent remove itens in head
});

Pjax.on("handler", function (hdata, config, done, fail) {
    setTimeout(function () {
        done(hdata.url, '<div id="pjax-container">Foo: ' + new Date() + '</div>', config, hdata.state);
    }, 1000);
});
0.6.6

7 months ago

0.6.5

8 months ago

0.6.4

3 years ago

0.6.3

3 years ago

0.6.2

3 years ago

0.6.1

3 years ago

0.6.0

4 years ago

0.5.6

4 years ago

0.5.5

5 years ago

0.5.2

5 years ago

0.4.5

7 years ago

0.4.4

7 years ago

0.4.3

7 years ago