search

What is Pjax

Nov 22, 2016 pm 01:46 PM
ajaxjspjax

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()

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)
}

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)

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)
}

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)
}

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)
      }
      ...
    }
  }
}

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)/)

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

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!


Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft