PushState + Ajax simple SPA example for single page Applications

Source: Internet
Author: User

SPA (Single Page Application) is short for SPA. Applications built using SPA have good user experience and high speed, so you do not need to reload the entire Page for content changes, this avoids unnecessary jump and repeated rendering, which reduces the server pressure. SPA is widely used on mobile WEB terminals.

In the previous article, we used Javascript to implement the frontend routing mentioned in the simple frontend routing. Without refreshing the entire page, we can transform the hash in the address bar to implement partial page loading.
Today, I want to introduce you to the effect of using the HTML5 PushState + ajax to not refresh the entire page, but the address bar transformation and partial page refreshing, A simple SPA is implemented based on the frontend and backend page technology. Let's first understand several knowledge points.
HTML5 History API
HTML5 adds the pushState method to History. This method adds the current url to the History record and modifies the current url to a new url. Of course, this method only modifies the Url display in the address bar, but does not send any request. Therefore, we can use this method in combination with ajax to implement SPA for a single page, that is, PushState + Ajax, called Pjax.
How to use pushstate:
History. pushState (state, title, url)
State: you can store any data you want. It will be appended to a new url to supplement the page information.
Title: As the name implies, it is document. title.
Url: new url, that is, the url to be displayed in the address bar.
History. replaceState (state, title, url)
The replaceState method is similar to pushState. The difference is that pushState adds the current url to the history record and then modifies the url. replaceState only modifies the url and does not add the history record.
Window. onpopstate
Generally, the popstate event is triggered whenever the url changes. But if pushState is called to modify the url, this event will not be triggered, so we can use it as the browser's forward and backward events. This event has a parameter that is the first parameter state of the pushState method above.
What can Pjax do?
Pjax is an excellent solution. It can do the following:
You can smoothly transition between page switches to add a Loading animation.
Data can be transmitted between pages without relying on URLs.
It can be selectively retained, such as a music website. When you switch to a page, it does not stop playing songs.
All tags can be used for jump, not just a tag.
This avoids repeated execution of common JS, reduces the request volume, saves traffic, and speeds up page response.
SEO is not affected. For browsers that do not support HTML5 and search engine crawlers, you can jump to the real page.
The browser supports the forward and backward buttons.
Implementation principle
1. Intercept the default jump action of Tag.
2. Use Ajax to request a new page.
3. Replace the returned Html with the page.
4. Use the HTML5 History API or Url Hash to modify the Url.
Code implementation
We set a Menu # nav, and load the corresponding content of the link page to div # result by clicking the link on the menu.
<Ul id = "nav">
<Li> <a href = "home.html"> homepage </a> </li>
<Li> <a href = "product.html"> Product </a> </li>
<Li> <a href = "server. php" title = "service"> Service </a> </li>
<Div id = "result"> </div>
Pjax. js
First, determine the browser's support for html5 in pjax. js, then define a cache object: cache {}, and define how to set and obtain the cache. Define the event object: event {} and bind the popstate, hashchange, and click events. The click event triggers the call to the pajax object and request the page content. You can download the source code of the cache object and event object. This article only sticks the core pjax {} object code for space reasons.
Var pjax = {
// Forward And Back, indicating whether the current operation is triggered by Forward And backward
Fnb: false,
// Display the content of the new page
Show: function (title, html ){
Document. title = title;
Document. querySelector ('# result'). innerHTML = html;
// Jump to the specified page
Jump: function (url, data, callback ){
// If it is triggered by forward and backward, try to get data from the cache
If (pjax. fnb ){
Var value = cache. get (url );
If (value! = Null ){
Pjax. show (value. title, value.html );
Document. querySelector ('# result'). innerHTML =' loading ...';
// Send a request using ajax
Var xhr = new XMLHttpRequest ();
Xhr. open ("GET", url, true );
Xhr. setRequestHeader ("X-PJAX", "true ");
Xhr. setRequestHeader ("X-PJAX-TITLE", data );
Xhr. setRequestHeader ("X-Requested-With", "XMLHttpRequest ");
Xhr. onreadystatechange = function (){
If (xhr. readyState === 4 ){
If (xhr. status> = 200 & xhr. status <300 | xhr. status = 304) {// 304 indicates the cache
Var html = xhr. responseText,
Title = xhr. getResponseHeader ("X-PJAX-TITLE ");
If (title = null ){
Title = document. title;
} Else {
Title = decodeURI (title );
// Console. log (title );
// Display the new page
Pjax. show (title, html );
// Not triggered by the forward and backward buttons
If (! Pjax. fnb ){
// Modify the URL. The URL address bar changes.
If (support = 'HTML5 '){
History. pushState (null, null, url );
} Else {
Var path = url. replace (location. protocol + "//" + location. host ,"");
Location. hash = path;
// Add to cache
Cache. set (url ,{
Title: title,
Html: html
} Else {
Console. log ('request failed! ');
Pjax. fnb = true;
Xhr. send ();
Init: function (){
Event. bindEvent ();
It can be seen that the core part of pjax is to send asynchronous ajax requests, call the history. pushState () method of html5, cache page information, and have processed the results returned by asynchronous requests.
Last call:
Pjax. init ();
Well, the above is a simple single page instance, and the code looks a little rough. You are welcome to correct and optimize it. Next, I will share with you some articles about the elegant single page application instances implemented by common front-end frameworks, stay tuned.

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.