Home > Web Front-end > JS Tutorial > body text

What is Pjax

伊谢尔伦
Release: 2016-11-22 13:46:18
Original
2529 people have browsed it

What is pjax?

Many websites (facebook, twitter) now support such a browsing method. When you click on a link in the site, it does not jump to the page, but just refreshes the page in the site. This kind of user experience is much better than having the entire page flash.

There is a very important part. The ajax refresh of these websites supports browser history. When refreshing the page, the address in the browser address field will also change. You can also use the browser's rollback function to go back. Return to the previous page.

So if we want to implement such a function, how do we do it?

I found that pjax provides a script to support such functionality.

The pjax project address is https://github.com/defunkt/jquery-pjax. For the actual effect, see: http://pjax.heroku.com/ When pjax is not checked, clicking the link will jump. After checking, the links will become ajax refreshed.

Why use pjax?

pjax has several benefits:

User experience improvement. When the page jumps, the human eye needs to re-identify the entire page. When refreshing part of the page, only one area needs to be re-identified. Since I used pjax technology on my website, I can't help but feel that it is much more uncomfortable to visit other websites that only have page jumps. At the same time, since a loading prompt is provided when refreshing some pages, and the old page is still displayed in the browser when refreshing, users can tolerate longer page loading times.

Greatly reduce bandwidth consumption and server consumption. Since only part of the page is refreshed, most of the requests (css/js) will not be re-obtained, and the outer frame part of the website with user login information does not need to be regenerated. Although I have not specifically counted the consumption of this part, I estimate that at least 40% of the requests and more than 30% of the server consumption have been saved.

I think there are also disadvantages:

Although I have not actually tested the support of historical browsers such as IE6, because pjax utilizes new standards, there will be issues with compatibility with older browsers. However, pjax itself supports fallback. When it is found that the browser does not support this function, it will jump back to the original page.

Complex server-side support The server-side needs to determine whether to render full page or partial page based on the incoming request. Relatively speaking, the system complexity increases. However, for well-designed server code, supporting such functionality should not be a big problem.

Taken together, due to the improvement of user experience and resource utilization, the disadvantages can be completely compensated. I highly recommend everyone to use it.

How to use pjax?

Just look at the official documentation.

I think technical people should develop the habit of reading first-hand technical information.

There is a rails gem plug-in for pjax that can be used directly. There is also django support.

Principle of pjax

In order to be able to deal with the problem, we need to be able to understand how pjax works. There is only one file of pjax code: https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js

If you have the ability, you can take a look at it yourself. Let me explain the principle here.

First, we specify in the html what the link content needs to be pjaxed, and the part that needs to be updated after clicking (put it in the data-pjax attribute):

$('a[data-pjax]').pjax()
Copy after login

When the pjax script is loaded, it will intercept these The linked event is then wrapped into an ajax request and sent to the server.

$.fn.pjax = function( container, options ) {
  return this.live('click.pjax', function(event){
    handleClick(event, container, options)
  })
}
function handleClick(event, container, options) {
  $.pjax($.extend({}, defaults, options))
  ...
  event.preventDefault()
}
var pjax = $.pjax = function( options ) {
  ...
  pjax.xhr = $.ajax(options)
}
Copy after login

This request carries the HEADER logo of X-PJAX. When the server receives such a request, it knows that it only needs to render part of the page and return it.

xhr.setRequestHeader('X-PJAX', 'true')
xhr.setRequestHeader('X-PJAX-Container', context.selector)
Copy after login

After pjax receives the returned request, it updates the area specified by data-pjax and also updates the browser's address.

options.success = function(data, status, xhr) {
  var container = extractContainer(data, xhr, options)
  ...
  if (container.title) document.title = container.title
  context.html(container.contents)
}
Copy after login

In order to support the browser's retreat, the history API is used to record the corresponding information.

pjax.state = {
  id: options.id || uniqueId(),
  url: container.url,
  container: context.selector,
  fragment: options.fragment,
  timeout: options.timeout
}
if (options.push || options.replace) {
  window.history.replaceState(pjax.state, container.title, container.url)
}
Copy after login

When the browser retreats, it intercepts the event and generates a new ajax request based on the recorded historical information.

$(window).bind('popstate', function(event){
  var state = event.state
  if (state && state.container) {
    var container = $(state.container)
    if (container.length) {
      ...
      var options = {
        id: state.id,
        url: state.url,
        container: container,
        push: false,
        fragment: state.fragment,
        timeout: state.timeout,
        scrollTo: false
      }
      if (contents) {
        // pjax event is deprecated
        $(document).trigger('pjax', [null, options])
        container.trigger('pjax:start', [null, options])
        // end.pjax event is deprecated
        container.trigger('start.pjax', [null, options])
        container.html(contents)
        pjax.state = state
        container.trigger('pjax:end', [null, options])
        // end.pjax event is deprecated
        container.trigger('end.pjax', [null, options])
      } else {
        $.pjax(options)
      }
      ...
    }
  }
}
Copy after login

In order to support fallback, one is to determine whether the browser supports the history pushstate API when loading:

// Is pjax supported by this browser?
$.support.pjax =
  window.history && window.history.pushState && window.history.replaceState
  // pushState isn't reliable on iOS until 5.
  && !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/)
Copy after login

The other is to directly jump to the page when it is found that there is no reply to the request for a period of time (you can set the parameter timeout).

options.beforeSend = function(xhr, settings) {
  if (settings.timeout > 0) {
    timeoutTimer = setTimeout(function() {
      if (fire('pjax:timeout', [xhr, options]))
        xhr.abort('timeout')
    }, settings.timeout)
    // Clear timeout setting so jquerys internal timeout isn't invoked
    settings.timeout = 0
Copy after login

Conclusion

Now that you have seen this, why don’t you actually use pjax? There are so many benefits, I think almost all websites should use pjax. Use it now!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template