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!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor