Do not refresh and change URL: pushstate + Ajax

Source: Internet
Author: User

If you have been to Google + and saw a new Youtube interface, you will experience this HTML5 new feature. With pushstate + Ajax (pjax), you can load web pages through Ajax. At the same time, you can change the URL without showing signs of page Jump refreshing. This is like changing the hash (#) of a Web page (#) same.

Guide/jump

  • 1. Old Solution
  • 2. New Solution: pushstate
    • 2.1 HTML5 pushstate + Ajax
    • 2.2 pushstate example
    • 2.3 demo
    • 2.4 replacestate
    • 2.5 differences between pushstate and replacestate
  • 3 restrictions
  • 4 Examples of Ajax and pushstate
  • 5 pushstate and popstate listeners
    • 5.1 Flowchart
  • 6 jquery + pjax plug-in
Old Solution

I once said that Seo and Ajax are natural enemies. Previously, the Ajax + hash method was popular for calling content from Twitter. The solution provided by Google is "#!~ String"Automatically converted to"? _ Excaped_fragment _ =~ StringTo capture dynamic content. But this will undoubtedly be very troublesome: First you need to "? _ Excaped_fragment _ =~ String"Processing configuration, and if the user puts the URL" http://example.com /#! /~ String"Directly copy and share, it means that the web page must also listen to hashchange. But if you think this #! It's okay if it looks nice.

New Solution: pushstate

However, the new HTML5 interface pushstate/replacestate can solve the problem perfectly. It avoids the problem of changing the hash and avoids users' doubts about the URL format, at the same time, the onpopstate provides a listener, and a good response is sent back. In addition, this URL does not need to actually exist.

HTML5 pushstate + Ajax

HTML5 provides the history interface to add or replace a URL in the form of state in the browser. Its implementation functions are pushstate and replacestate.

Pushstate example

The basic parameters of pushstate () are:

Window. History. pushstate (State, title, URL );

Both State and title can be empty, but it is not recommended to be empty. You should create a State to use with the popstate listener.

For example, we use pushstate to change the URL without refreshing the page.

VaR state = ({

URL:~ Href, Title:~ Title,~ Additionalkey:~ Additionalvalue

});

Window. History. pushstate (state,~ Title,~ Href);

Contains "~" It indicates the custom content. You can~ Href(URL) is pushed to the history of the browser. To change the webpage title, you should:

Document. Title =~ Newtitle;

Note that only pushstate cannot change the webpage title.

Demo

Click here to try(Implementation function onclick = history. pushstate (null, null, '/test-string ');). In fact, this blog also deploys this technology between articles.

Likewise, replacestate

Window. History. replacestate (state,~ Title,~ Href);

Differences between pushstate and replacestate

Pushstate () can be used to create a history. It can be used with a popstate event, while replacestate () replaces the current URL without generating a history.

Restrictions

You can only replace the http://baidu.com with a URL of the same domain, for example, you cannot replace the http://google.com with. In addition, the State object does not store non-serializable objects such as Dom.

Example of how Ajax works with pushstate

Now we use Ajax + pushstate to provide a brand new Ajax call style. Taking jquery as an example, you should add a method for onclick of the a tag for Seo purposes.

$ ("~ TargetA "). Click (function (EVT ){

EVT. preventdefault (); // block the default redirect operation

VaR uri = $ (this). ATTR ('href ');

VaR newtitle = ajax_load (URI); // your custom Ajax loading function. For example, it returns newtitle

Document. Title = newtitle; // assign a new page title

If (history. pushstate ){

VaRState= ({

URL: URI, Title: newtitle

});

Window. History. pushstate (State, Newtitle, Uri );

} Else {window. Location. href = "#! "+~ Fakeuri;} // If not, use the old solution

Return false;

});

Function ajax_load (URI) {... return newtitle;} // your custom Ajax function. For example, it returns newtitle

To complete pushstate. As for how to obtain the new title newtitle, you can assign data-newtitle = ~ to the tag ~ The title attribute is read at that time, or if you use the $. Ajax () function, you can use $ (result). Filter ("title"). Text () to obtain it.

In addition, if you want to use Ajax for the connection to the newly loaded page, you need to redeploy the tag of the new content, such

$ ("~ NewcontenttargetA "). Click (function (EVT ){...});

Pushstate and popstate listeners

To better support the browser's historical forward and backward operations, you should deploy a popstate listener:

Window. addeventlistener ('popstate', function (EVT ){

VaR state = EVT. State;

VaR newtitle = ajax_load (State. url); // your custom Ajax loading function. For example, it returns newtitle

Document. Title = newtitle;

}, False );

Note: You can use setRequestHeader () to allow the server to work with your Ajax request to output special content.

Flowchart

Shows the general process of this example.

Jquery + pjax plug-in

It has been released on GitHub. Someone has made pjax A jquery plug-in to facilitate calling and save a lot of code:

If ($. Support. pjax ){

$ (Document). On ('click', 'a [data-pjax] ', function (event ){

VaR Container = $ (this). Closest ('[data-pjax-container]')

$. Pjax. Click (event, {container: Container })

});}

Thank you for watching. If any error occurs, please point it out.

 

Http://blog.netsh.org/posts/pushstate-ajax_1339.netsh.html

Do not refresh and change URL: pushstate + Ajax

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.