What is Pjax?

Source: Internet
Author: User
What is pjax? Many websites (facebook, & amp; nbsp; twitter) now support this kind of browsing method. When you click a link in the site, it is not a page Jump, instead, refresh the website page. Such a user body...

What is pjax?

Many websites (facebook and twitter) now support this kind of browsing method. When you click a link in a site, it is not a page Jump, but a page refresh in the site. This user experience is much better than the whole page.

There is a very important component. The ajax refresh of these websites supports the browser history. When refreshing the page, the address above the browser address bar will also be changed, the browser's rollback function can also be used to roll back to the previous page.

So what should we do if we want to implement such a function?

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

The pjax Project address is in the https://github.com/defunkt/jquery-pjax. See the actual effect: http://pjax.heroku.com/When pjax is not checked, click the link is jump. After the check box is selected, the link is changed to ajax refresh.

Why pjax?

Pjax has several advantages:

Improved user experience. When a page is redirected, the human eye needs to re-Identify the entire page. When refreshing some pages, only one area needs to be re-identified. Since I used the pjax Technology on my website, I cannot help but feel a lot more uncomfortable when I access other websites that only have page jumps. At the same time, because a loading prompt is provided when some pages are refreshed, and the old pages are still displayed in the browser when the pages are refreshed, users can tolerate longer page loading times.

Greatly reduce bandwidth consumption and server consumption. Because only some pages are refreshed, most requests (css/js) will not be retrieved again, and the external boxes with user login information on the website do not need to be regenerated. Although I did not specifically count the consumption of this part, I estimate there are at least 40% of requests, and more than 30% of server consumption is saved.

I think there are also:

Although I have not actually tested the support of historical browsers such as IE6, the compatibility of old browsers may be problematic due to the use of new standards by pjax. However, pjax itself supports fallback. When the browser finds that this function is not supported, it will return to the original page Jump.

The complex server side supports the server side to determine whether to perform full page rendering or partial page rendering based on the request. The system complexity is increased. However, for well-designed server code, supporting such a function won't be too problematic.

In combination, the disadvantages of user experience and resource utilization can be completely compensated. I strongly recommend that you use it.

How to Use pjax?

Simply read the official documentation.

I think people who are skilled should develop the habit of reading technical materials.

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

Pjax principles

To be able to solve the problem, we need to be able to understand how pjax works. Pjax code has only one file: https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js

If you have the ability, you can check it again by yourself. I will explain the principle here.

First, we will specify in html what is the link content of pjax and what needs to be updated after clicking it (in the data-pjax attribute ):

$('a[data-pjax]').pjax()

After the pjax script is loaded, it intercepts the events of these links, encapsulates them into an ajax request, and sends it 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)}

The request carries the HEADER identifier of the X-PJAX, and the server knows that it only needs to render part of the page to return when receiving such a request.

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

After pjax accepts the returned request, it updates the region specified by data-pjax and the browser address.

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

In order to support browser fallback, 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)}

When the browser returns, 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)      }      ...    }  }}

To support fallback, one is to judge whether the browser supports the history pushstate API during 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)/)

In addition, when a request is not responded for a period of time (the timeout parameter can be set), the page is redirected directly.

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

Conclusion

Since we can see it all, why don't you actually use pjax? With so many benefits, I think almost all websites should adopt pjax. Use it now!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.