PushState + Ajax achieve a simple one-page application SPA

 

 

Single-page application (Single Page Application) referred to SPA, the application advantages of using SPA has built a good user experience, fast, does not need to change the contents of the entire page to reload, jump and avoid unnecessary repetition rendering, thus reducing the relative server stress, SPA in the WEB mobile terminal is widely used.

We realize Javascript front-end routing simple front-end routes mentioned in the previous article, may, without refreshing the entire page, partial page load is achieved by hash transformation address bar.

Today I give you about is the use of PushState HTML5 + ajax implementation does not refresh the entire page, while the address bar, transform, partial page refresh effect, integrated front and back end technology to achieve a simple page of SPA. We start to understand some knowledge points.

HTML5 History API

HTML5 History in an increase in pushState method, which will be added to the current url history, and then modify the current url to a new url. Of course, this method will only modify the Url address bar display, but did not issue any request. So we can use this method in conjunction with ajax single-page application SPA, is PushState + Ajax, called Pjax.

pushstate use:

history.pushState(state, title, url)

state:  you can put any data you want to put, it will attach to the new url, as a supplement to the information page.

title:  As the name suggests, is document.title.

url:  new url, that is, you want to display on the url in the address bar.

history.replaceState(state, title, url)

replaceState methods and pushState much the same, only difference is that the current url pushState will add to the historical record, and then edit your url, and replaceState just modify url, do not add the historical record.

window.onpopstate

In general, whenever the url changes, popstate event will be triggered. But if the call pushState to modify url, the event is not triggered, so we can use it as a forward-reverse event browser. The event has one parameter, the first parameter state pushState above method.

What do Pjax

Pjax is an excellent solution that can be done:

  • Smooth transition can switch between pages, increase Loading animation.
  • Can pass data between the pages, do not rely URL.
  • Can selectively hold, such as music site, you will not stop playing the song when switching pages.
  • All the tags can be used to jump, just a label.
  • JS avoid repeated public, reducing the volume of requests, save traffic, speed up page response times.
  • For SEO also not be affected, that do not support HTML5 browsers and search engine crawlers, you can jump real page.
  • Support browser forward and back buttons.

The principle

1. intercept a default tag jump operation.

2. Ajax request a new page.

3. Replace Html returned to the page.

4. Use of HTML5 History API or the Url Url Hash modified.

Code

HTML

We set up a menu #nav, through a link on the menu, loads the linked pages corresponding to the contents of the div # result.

Copy the code
<ul id="nav">  
    <li><a href="home.html">首页</a></li>  
    <li><a href="product.html">产品</a></li>  
    <li><a href="server.php" title="服务">服务</a></li>  
</ul> 
<div id="result"></div>
Copy the code

pjax.js

First, it is determined in the case pjax.js support html5 browser then define a cache object cache: cache {}, the definition set cache and the cache acquisition method. Then define event event object: event {}, binding popstate and hashchange and click event, click the event will trigger a call pajax object request page content. cache cache object code that event and the event object you can download the source code view, this paper due to space reasons only the core pjax {} object code stick out.

Copy the code
pjax = {var 
    // Forward And the Back, indicates whether the current operation is triggered by the advance and retract 
    FNB: to false, 
    // display a new page content 
    Show: function (title, HTML) { 
        document.title = title; 
        document.querySelector ( '# Result ') = the innerHTML HTML;. 
    }, 
 
    // skip to a specific page 
    Jump: function (URL, data, the callback) { 
         
        // if it is triggered by forward and backward, then try to get the data from the cache 
        if (pjax.fnb ) { 
            var value = cache.get (URL); 
            IF (value == null) {! 
                pjax.show (value.title, value.html); 
                return; 
            } 
        }
 
 
        document.querySelector ( '# Result') = the innerHTML. 'Loading...'; 
        // Ajax transmission request 
        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是缓存 
                    var html = xhr.responseText, 
                        title = xhr.getResponseHeader("X-PJAX-TITLE"); 
                    if(title==null){ 
                        title = document.title; 
                    }else{ 
                        = decodeURI title (title); 
                    } 
                    //console.log(title); 
                     
                    // display the new page 
                    pjax.show (title, HTML); 
 
                    // instead of forward and back buttons trigger 
                    IF (pjax.fnb) {! 
                        // modify the URL , URL address bar will transform 
                        IF (Support === 'the HTML5') { 
                            history.pushState (null, null, URL); 
                        } the else { 
                            var path = url.replace (location.protocol + "//" + location.host , ""); 
                            the location.hash = path; 
                        } 
                        // added to the cache 
                        cache.set (URL, { 
                            title: title, 
                            HTML: HTML 
                        }); 
                    } 
 
                } {the else 
                    the console.log ( '! request failure'); 
                } 
                pjax.fnb = to true; 
            } 
        }; 
        xhr.send (); 
    }, 
 
    the init: function () { 
        event.bindEvent (); 
    } 
};
Copy the code

It can be seen that the core part pjax ajax asynchronous request, the call html5 history.pushState () method, cache page information, the processing result has been returned from the asynchronous request.

Last call:

pjax.init();

 

 

Single-page application (Single Page Application) referred to SPA, the application advantages of using SPA has built a good user experience, fast, does not need to change the contents of the entire page to reload, jump and avoid unnecessary repetition rendering, thus reducing the relative server stress, SPA in the WEB mobile terminal is widely used.

We realize Javascript front-end routing simple front-end routes mentioned in the previous article, may, without refreshing the entire page, partial page load is achieved by hash transformation address bar.

Today I give you about is the use of PushState HTML5 + ajax implementation does not refresh the entire page, while the address bar, transform, partial page refresh effect, integrated front and back end technology to achieve a simple page of SPA. We start to understand some knowledge points.

HTML5 History API

HTML5 History in an increase in pushState method, which will be added to the current url history, and then modify the current url to a new url. Of course, this method will only modify the Url address bar display, but did not issue any request. So we can use this method in conjunction with ajax single-page application SPA, is PushState + Ajax, called Pjax.

pushstate use:

history.pushState(state, title, url)

state:  you can put any data you want to put, it will attach to the new url, as a supplement to the information page.

title:  As the name suggests, is document.title.

url:  new url, that is, you want to display on the url in the address bar.

history.replaceState(state, title, url)

replaceState methods and pushState much the same, only difference is that the current url pushState will add to the historical record, and then edit your url, and replaceState just modify url, do not add the historical record.

window.onpopstate

In general, whenever the url changes, popstate event will be triggered. But if the call pushState to modify url, the event is not triggered, so we can use it as a forward-reverse event browser. The event has one parameter, the first parameter state pushState above method.

What do Pjax

Pjax is an excellent solution that can be done:

  • Smooth transition can switch between pages, increase Loading animation.
  • Can pass data between the pages, do not rely URL.
  • Can selectively hold, such as music site, you will not stop playing the song when switching pages.
  • All the tags can be used to jump, just a label.
  • JS avoid repeated public, reducing the volume of requests, save traffic, speed up page response times.
  • For SEO also not be affected, that do not support HTML5 browsers and search engine crawlers, you can jump real page.
  • Support browser forward and back buttons.

The principle

1. intercept a default tag jump operation.

2. Ajax request a new page.

3. Replace Html returned to the page.

4. Use of HTML5 History API or the Url Url Hash modified.

Code

HTML

We set up a menu #nav, through a link on the menu, loads the linked pages corresponding to the contents of the div # result.

Copy the code
<ul id="nav">  
    <li><a href="home.html">首页</a></li>  
    <li><a href="product.html">产品</a></li>  
    <li><a href="server.php" title="服务">服务</a></li>  
</ul> 
<div id="result"></div>
Copy the code

pjax.js

First, it is determined in the case pjax.js support html5 browser then define a cache object cache: cache {}, the definition set cache and the cache acquisition method. Then define event event object: event {}, binding popstate and hashchange and click event, click the event will trigger a call pajax object request page content. cache cache object code that event and the event object you can download the source code view, this paper due to space reasons only the core pjax {} object code stick out.

Copy the code
pjax = {var 
    // Forward And the Back, indicates whether the current operation is triggered by the advance and retract 
    FNB: to false, 
    // display a new page content 
    Show: function (title, HTML) { 
        document.title = title; 
        document.querySelector ( '# Result ') = the innerHTML HTML;. 
    }, 
 
    // skip to a specific page 
    Jump: function (URL, data, the callback) { 
         
        // if it is triggered by forward and backward, then try to get the data from the cache 
        if (pjax.fnb ) { 
            var value = cache.get (URL); 
            ! IF (value == null) { 
                pjax.show (value.title, value.html); 
                return; 
            } 
        } 
 
 
        document.querySelector ( '# Result') = the innerHTML. 'Loading...'; 
        // Ajax transmission request 
        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是缓存 
                    var html = xhr.responseText, 
                        title = xhr.getResponseHeader("X-PJAX-TITLE"); 
                    if(title==null){ 
                        title = document.title; 
                    }else{ 
                        = decodeURI title (title); 
                    } 
                    //console.log(title); 
                     
                    // display the new page 
                    pjax.show (title, HTML); 
 
                    // instead of forward and back buttons trigger 
                    IF (pjax.fnb) {! 
                        // modify the URL , URL address bar will transform 
                        IF (Support === 'the HTML5') { 
                            history.pushState (null, null, URL); 
                        } the else { 
                            var path = url.replace (location.protocol + "//" + location.host , ""); 
                            the location.hash = path; 
                        } 
                        // added to the cache 
                        cache.set (URL, { 
                            title: title,
                            HTML: HTML 
                        }); 
                    } 
 
                } {the else 
                    the console.log ( 'Request failed!'); 
                } 
                pjax.fnb = to true; 
            } 
        }; 
        xhr.send (); 
    }, 
 
    the init: function () { 
        event.bindEvent () ; 
    } 
};
Copy the code

It can be seen that the core part pjax ajax asynchronous request, the call html5 history.pushState () method, cache page information, the processing result has been returned from the asynchronous request.

Last call:

pjax.init();

 

Guess you like

Origin www.cnblogs.com/sishahu/p/12618102.html