HTML 5 History API's "former present"

Source: Internet
Author: User

Original: An Introduction to the HTML5 history API

Description of the HTML 5 history API

Translator: Dwqs

History is interesting, isn't it? In previous versions of HTML, we had very limited access to browsing history. We can use the methods we can use back and forth, but that's all we can do.

However, with the history API of HTML 5, we have better control over the browser's historical record. For example: We can add a record to a list of history, or update the URL of the address bar when there is no refresh.

Why introduce the history API?

In this article, we'll look at the source of the history API in HTML 5. Before that, we often used hash values to change the content of the page, especially those that were particularly important to the page. Because there is no refresh, it is not possible to change the URL for a single-page application. Also, when you change the hash value of a URL, it has no effect on the browser's history.

These are now easy to implement for the history API for HTML 5, but it may require additional development scripts because a single-page application does not necessarily use hash values. It also allows us to build new applications in a SEO-friendly way. In addition, it can reduce the bandwidth, but how to prove it?

In this article, I'll develop a single-page application with the history API to prove the problem.

This also means that I must first load the necessary resources on the homepage. Starting now, the page simply loads the content that you want. In other words, the app does not load all the content from the beginning, and it is loaded when the second app content is requested.

Note that you need to perform some server-side coding to provide only a subset of the resources, rather than the full page content.

Browser support

in writing this article, the mainstream browser support for the history API is very good, you can click here to see its support, this link will tell you to support the browser, and before using, there is always good practice to detect the specific features supported.

In order to determine whether the browser supports this API in a way that can be checked with the following line of code:

return  !! (Window.history && history.pushstate);

In addition, I suggest that you refer to this article: Detect support for Various HTML5 Features. (PS: subsequent translation)

If you are using a modern browser, you can use the following code:

if (modernizr.history) {    //History API supported}

If your browser does not support the history API, you can use History.js instead.

Use history

HTML 5 provides two new methods:

1, history.pushstate (); 2, History.replacestate ();

Both of these methods allow us to add and update history, and they work the same way and can add the same number of parameters. In addition to the method, there are popstate events. The following article describes how and when to use the popstate event.

As with the pushstate () and replacestate () parameters, the parameters are described as follows:

1. State: stores the JSON string, which can be used in the popstate event.

2,title: Now most browsers do not support or ignore this parameter, it is best to use NULL instead

3,URL: Any valid URL, used to update the browser's address bar, and do not care whether the URL already exists in the address list. More importantly, it does not reload the page.

The main difference between the two methods is thatpushstate () is adding a new entry in the history stack, and Replacestate () is replacing the current record value . If you are still confused about this, use some examples to prove the difference.

Let's say we have two stacks, one labeled 1, the other marked 2, you have a third stack block, and you have a tag of 3. When pushstate () is executed, the stack block 3 is added to the existing stack, so the stack has 3 blocks.

The same hypothetical scenario, when executing replacestate () , will be on the stack of Block 2 and place block 3. So the number of records in history is constant, that is,pushstate () will add 1 to the number of histories.

Comparison results such as:

In order to control the browser's history, we have ignored the events of pushstate () and replacestate () . But suppose the browser counts a lot of bad records, the user may be redirected to those pages, or not. In this case, an unexpected problem arises when the user uses the browser's forward and back navigation buttons.

Although we expect the Popstate event to be triggered when we are working with pushstate () and replacestate () . But in fact, this is not the case. Conversely,popstate is triggered when you browse the session history, whether you click the Forward or Back button, or use the History.go and History.back methods.

In WebKit browsers, a popstate event would is triggered after document's onload event, but Firefox and IE does not has this Behavior. (in WebKit Browser, the Popstate event is triggered after the OnLoad event in document, and Firefox and IE do not).

Demo sample

HTML:

<Div class= "Container">    <Div class= "Row">        <ul class= "Nav navbar-nav">            <Li><a href= "home.html" class= "Historyapi">Home</a></Li>            <Li><a href= "about.html" class= "Historyapi">About</a></Li>            <Li><a href= "contact.html" class= "Historyapi">Contact</a></Li>        </ul>    </Div>    <Div class= "Row">        <Div class= "Col-md-6">            <Div class= "Well">Click on the Links above to see the history API usage using<Code>Pushstate</Code>Method.</Div>        </Div>        <Div class= "Row">               <Div class= "Jumbotron" ID= "Contentholder">                <H1>home!</H1>                <P>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</P>            </Div>        </Div>    </Div></Div>

Javascript:

<script type="Text/javascript"> JQuery (' Document '). Ready (function() {JQuery ('. Historyapi '). On (' click ',function(e) {E.preventdefault ();varhref = $ ( This). attr (' href ');//Getting Contentgetcontent (HREF,true); JQuery ('. Historyapi '). Removeclass (' Active '); $( This). AddClass (' Active ');             }); });//Adding Popstate event listener to handle browser back buttonWindow.addeventlistener ("Popstate",function(e) {//Get state value using E.stateGetContent (Location.pathname,false); });functionGetContent (URL, addentry) {$.get (URL). Done (function(data) {//Updating Content on Page$(' #contentHolder '). HTML (data);if(AddEntry = =true) {//ADD history Entry using PushstateHistory.pushstate (NULL,NULL, URL);    }                     }); }</script>

Demo 1:html 5 history api–pushstate

History entries are calculated in the browser and can be easily used by the browser's forward and back buttons. View Demo (PS: When you click on the Demo1 tab, its record will be added to the browser's history, and when you click the Back/Forward button, you can go back/jump to the tab corresponding to the one you clicked before)

Demo 2:html 5 History api–replacestate

History entries are updated in the browser and cannot be browsed using the browser's forward and back buttons. View Demo (PS: When you click on the Demo1 tab, its record will be replaced by the current browser's history, when you click the Back/Forward button, you can not go back/jump to the tab you clicked before the corresponding page, but return/jump to the previous page you entered Demo2)

Summary (PS: like these two words ~ ~ ~ ^_^ ~ ~ ~)

The history API in HTML 5 has a big impact on Web applications. To make it easier to create an efficient, SEO-friendly single-page application, it removes the dependency on the hash value.

Next: You in the Blog collection?

HTML 5 History API's "former present"

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.