Pushstate+ajax implementation of a simple single page application spa

Source: Internet
Author: User

Http://www.helloweba.com/view-blog-386.html

Single page application is the spa, the application built using the SPA has the advantage of user experience, fast, content changes do not need to reload the entire page, avoid unnecessary jumps and repeated rendering, thereby reducing the server pressure, The spa is widely used in web mobile applications.

In our previous article, JavaScript implements the front-end routing mentioned in the front-end simple route, which can be partially loaded by transforming the hash of the address bar without refreshing the entire page.

Today I would like to introduce to you is the use of HTML5 Pushstate+ajax implementation does not refresh the entire page, and Address bar transformation, page Local refresh effect, comprehensive front-end page technology to achieve a simple spa. Let's get to know a few points of knowledge first.

HTML5 History API

HTML5 adds the Pushstate method to the history, which adds the current URL to the historical record, and then modifies the current URL to the new URL. Of course, this method only modifies the URL display of the address bar, but does not make any requests. So we can use this method combined with Ajax to implement a single-page application spa, that is, Pushstate+ajax, person pjax.

How to use Pushstate:

History.pushstate (state, title, URL)

State : You can put any data you want, and it will be appended to the new URL as a supplement to the information on that page.

title: as the name implies, is document.title.

URL: The new URL, which is the URL you want to display on the address bar.

History.replacestate (state, title, URL)

The Replacestate method is similar to Pushstate, except that pushstate adds the current URL to the history, modifies the URL, and replacestate simply modifies the URL without adding a history.

Window.onpopstate

In general, popstate events are triggered whenever a URL changes. However, if you call pushstate to modify the URL, the event will not be triggered, so we can use it as the browser's forward and backward event. The event has a parameter, which is the first parameter state of the Pushstate method above.

What can pjax do?

Pjax is an excellent solution that it can do:

    • You can smooth transitions between page transitions, adding loading animations.
    • You can pass data between pages, without relying on URLs.
    • You can select a retention state, such as a music web site, to switch pages without stopping the song.
    • All tags can be used to jump, not just a tag.
    • Avoid the repeated execution of public JS, reduce the volume of requests, save traffic, speed up the page response.
    • SEO will not have an impact, for the browser does not support HTML5 and search engine crawler, you can jump to the real page.
    • Supports browser forward and back buttons.
Implementation principle

1. Intercept the default jump action for the a tag.

2. Use Ajax to request a new page.

3. Replace the returned HTML with the page.

4. Use HTML5 's history API or URL hash to modify the URL.

Code implementation

Html

We set up a menu #nav to load the contents of the link page into Div#result by clicking on the link on the menu.

<ulID= "NAV">      <Li><ahref= "home.html">Home</a></Li>      <Li><ahref= "product.html">Products</a></Li>      <Li><ahref= "server.php"title= "Service">Service</a></Li>  </ul> <DivID= "Result"></Div>

Pjax.js

First determine the browser support for HTML5 in Pjax.js, and then define a cache caching object: cache{}, which defines how to set the cache and get the cache. Then define the event events object: event{}, Bind Popstate and Hashchange, and the click event, the Click event Triggers the call to the Pajax object, requesting the page content. The cache cache object and event object code you can download source view, this article because of space reasons only the core pjax{} object code to stick out.

varPjax = {     //Forward and back, indicating whether the current operation is triggered by forward and backwardFnbfalse,     //Show New page contentShowfunction(title, html) {Document.title=title; Document.queryselector (' #result '). InnerHTML =html; },      //jump to the specified pageJumpfunction(URL, data, callback) {//If it is triggered by forward and backward, try to get the data from the cache        if(PJAX.FNB) {varValue =cache.get (URL); if(Value!==NULL) {pjax.show (value.title, value.html); return; }} document.queryselector (' #result '). InnerHTML = ' load in ... '; //Ajax sends requests        varXHR =NewXMLHttpRequest (); 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 >= && Xhr.status < | | xhr.status = = 304) {//304 is the cache                    varHTML =Xhr.responsetext, Title= Xhr.getresponseheader ("X-pjax-title"); if(title==NULL) {title=Document.title; }Else{title=decodeURI (title); }                     //Console.log (title);                                         //Show New Pagepjax.show (title, HTML); //not the forward and back button triggers                    if(!PJAX.FNB) {                         //Modifying the Url,url Address bar transforms                        if(Support = = = ' HTML5 ')) {history.pushstate (NULL,NULL, URL); } Else {                             varPath = Url.replace (Location.protocol + "//" + Location.host, "" "); Location.hash=path; }                         //Add to Cachecache.set (URL, {title:title, html:h                     TML}); }                  }Else{Console.log (' Request failed! ‘); } PJAX.FNB=true;         }         };     Xhr.send (); }, Init:function() {event.bindevent (); } };

As you can see, the core part of Pjax is sending asynchronous AJAX requests, calling HTML5 's History.pushstate () method, caching page information, and processing the results returned by an asynchronous request.

Last Call:

Pjax.init ();

Pushstate+ajax implementation of a simple single page application spa

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.