啥是pjax?

2019年12月21日 阅读数:43
这篇文章主要向大家介绍啥是pjax?,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

pjax = pushState + ajax

=======================javascript

pjax是一个jQuery插件,它使用ajax和pushState经过真正的永久连接,页面标题和后退按钮提供快速浏览体验。html

pjax的工做方式是经过ajax从服务器获取HTML,而后用加载的HTML替换页面上容器元素的内容。而后,它使用pushState更新浏览器中的当前URL。因为如下两个缘由,这致使页面导航更快:java

  • 没有页面资源(JS,CSS)被从新执行或从新应用;
  • 若是将服务器配置为使用pjax,则它只能渲染部分页面内容,所以避免了可能昂贵的完整布局渲染。

该项目的状态

此时,jquery-pjax基本上再也不须要维护。它可能会继续收到重要的错误修复,可是_其功能集被冻结_,不太可能得到新功能或加强功能。react

安装

pjax取决于jQuery 1.8或更高版本。jquery

$ npm install jquery-pjax

standalone script

Download and include jquery.pjax.js in your web page:git

curl -LO https://raw.github.com/defunkt/jquery-pjax/master/jquery.pjax.js

Usage

$.fn.pjax

The simplest and most common use of pjax looks like this:github

$(document).pjax('a', '#pjax-container')

This will enable pjax on all links on the page and designate the container as #pjax-container.web

If you are migrating an existing site, you probably don't want to enable pjax
everywhere just yet. Instead of using a global selector like a, try annotating
pjaxable links with data-pjax, then use 'a[data-pjax]' as your selector. Or,
try this selector that matches any <a data-pjax href=> links inside a `<div
data-pjax>` container:ajax

$(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container')

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. Here is an example of how this might be done in Ruby on Rails:npm

def index
  if request.headers['X-PJAX']
    render :layout => false
  end
end

If you'd like a more automatic solution than pjax for Rails check out [Turbolinks][].

Check if there is a pjax plugin for your favorite server framework.

Also check out RailsCasts #294: Playing with PJAX.

Arguments

The synopsis for the $.fn.pjax function is:

$(document).pjax(selector, [container], options)
  1. selector is a string to be used for click event delegation.
  2. container is a string selector that uniquely identifies the pjax container.
  3. options is an object with keys described below.
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 [$.ajax][]
dataType "html" see [$.ajax][]
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 is a lower level function used by $.fn.pjax itself. It allows you to get a little more control over the pjax event handling.

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

if ($.support.pjax) {
  $(document).on('click', 'a[data-pjax]', function(event) {
    var container = $(this).closest('[data-pjax-container]')
    var containerSelector = '#' + container.id
    $.pjax.click(event, {container: containerSelector})
  })
}

NOTE Use the explicit $.support.pjax guard. We aren't using $.fn.pjax so we should avoid binding this event handler unless the browser is actually going to use pjax.

$.pjax.submit

Submits a form via pjax.

$(document).on('submit', 'form[data-pjax]', function(event) {
  $.pjax.submit(event, '#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 ✔︎ xhr, options can set XHR headers
pjax:start xhr, options
pjax:send xhr, 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, xhr, options after replacing HTML content loaded from the server
pjax:timeout ✔︎ xhr, options fires after options.timeout; will hard refresh unless canceled
pjax:error ✔︎ xhr, textStatus, error, options on ajax error; will hard refresh unless canceled
pjax:complete xhr, textStatus, options always fires after ajax, regardless of result
pjax:end xhr, 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).on('pjax:send', function() {
  $('#loading').show()
})
$(document).on('pjax:complete', function() {
  $('#loading').hide()
})

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

$(document).on('pjax:timeout', function(event) {
  // Prevent default timeout redirection behavior
  event.preventDefault()
})

Advanced configuration

Reinitializing plugins/widget on new page content

The whole point of pjax is that it fetches and inserts new content without
refreshing the page. However, other jQuery plugins or libraries that are set to
react on page loaded event (such as DOMContentLoaded) will not pick up on
these changes. Therefore, it's usually a good idea to configure these plugins to
reinitialize in the scope of the updated page content. This can be done like so:

$(document).on('ready pjax:end', function(event) {
  $(event.target).initializeMyPlugin()
})

This will make $.fn.initializeMyPlugin() be called at the document level on
normal page load, and on the container level after any pjax navigation (either
after clicking on a link or going Back in the browser).

Response types that force a reload

By default, pjax will force a full reload of the page if it receives one of the
following responses from the server:

  • Page content that includes <html> when fragment selector wasn't explicitly
    configured. Pjax presumes that the server's response hasn't been properly
    configured for pjax. If fragment pjax option is given, pjax will extract the
    content based on that selector.
  • Page content that is blank. Pjax assumes that the server is unable to deliver
    proper pjax contents.
  • HTTP response code that is 4xx or 5xx, indicating some server error.

Affecting the browser URL

If the server needs to affect the URL which will appear in the browser URL after
pjax navigation (like HTTP redirects work for normal requests), it can set the
X-PJAX-URL header:

def index
  request.headers['X-PJAX-URL'] = "http://example.com/hello"
end

Layout Reloading

Layouts can be forced to do a hard reload when assets or html changes.

First set the initial layout version in your header with a custom meta tag.

<meta http-equiv="x-pjax-version" content="v123">

Then from the server side, set the X-PJAX-Version header to the same.

if request.headers['X-PJAX']
  response.headers['X-PJAX-Version'] = "v123"
end

Deploying a deploy, bumping the version constant to force clients to do a full reload the next request getting the new layout and assets.