About HTML5 's History API

Source: Internet
Author: User

Talking about the problem of paging from Ajax

Imagine that you are watching a video below the comment, and when you turn to page more than 10, you find a comment that is slightly longer, but very interesting. When you want to stop the wheel to look closely, the hand is pressed to the F5. Then the page refreshes and the comment goes back to the first page, so you have to re-turn it again.

Or, you want to send this comment to someone else to share it to someone else's page address (why not just copy it?) Because of the video and other scenes AH), and add a sentence: Please turn to the following comments on page xx xx.

That's the problem. Imagine if the browser can remember your current state (see page more than 10, for example), instead of restoring it on a refresh, does it seem much smarter?

Why use Ajax?

There is a reason to switch pages and other content with Ajax. In the traditional Ajax-free site, page A and page B may be only 10% different, the other 90% of content (especially navigation, footer and other common elements) are the same, but still need to download the browser and display a new whole page. If you use Ajax, not only save the browser need to download resources, and no refresh switch is significantly smoother and smoother than the page jump.

In the comments below, Ajax can be said to be necessary. Video of such heavyweight elements, will not be able to give you reload once, can not endure.

The desirability of a traditional jump page

Traditional sites that do not use Ajax, each page is a jump, then you can see in the browser address bar such as ?page=2 such parameters. Each page is marked by the URL of the address bar, and each time the request is made, the browser returns the correct page number based on the parameter.

Therefore, the traditional jump page, the refresh will not lose state.

Combine both

Now we can think of, if the AJAX update page local content, but also in the Address bar URL update status parameters, you can make a more perfect Ajax page.

However, JavaScript modifies location hash any properties except the outside, and the page reloads with the new URL. The only parameter that does not cause a flush is hash not sent to the server, so the server cannot get the status.

The HTML5 History API will then address this issue.

Introducing the HTML5 history API

The HTML5 history API consists of only 2 methods: history.pushState() and history.replaceState() , as well as 1 events: window.onpopstate .

History.pushstate ()

Its complete body is history.pushState(stateObject, title, url) , including three parameters.

The 1th parameter is a state object, which can be understood as an element that is used to store custom data. It is associated with both parameters as well url .

The 2nd parameter is the title, is a string, the current browser will ignore it (later it is possible to enable, as a page title), so it doesn't matter what is set. The currently recommended setting is an empty string.

The 3rd parameter is the URL address, which is typically the ?page=2 relative path to the simple style of the parameter, which is automatically benchmarked against the current URL. It is important to note that this parameter URL needs to be the same as the current page URL, otherwise an error will be thrown.

The calling pushState() method will be reborn as a history, allowing the browser's "back" and "forward" navigation ("back" is a fairly common button). In addition, from the URL of the same-origin policy can be seen, HTML5 History API's starting point is very clear, that is, no jump to a single site can also save its various states as the browser's multiple records. When the site is reloaded through history, the site can be loaded directly into the corresponding state.

History.replacestate ()

It is history.pushState() basically the same as the method, with only a little difference, history.replaceState() not a new history, but rather a replacement of the current history record.

Window.onpopstate

The opposite of push is pop, and you can guess that this event is triggered when the browser takes out history and loads. But in fact, its conditions are relatively harsh, almost only click on the browser's "forward", "back" these navigation buttons, or is called by JavaScript and history.back() other navigation methods, and before and after the handover of two historical records belong to the same Web document, the event will be triggered.

The "Same Web document" above is understood to be the same as the JavaScript environment document , not the same as the underlying URL (which removes various parameters). That is, whenever a reload occurs (whether it's jumping to a new site or continuing on the site), the JavaScript Global environment changes and popstate events are not triggered.

popstateThe event is designed and used in conjunction with the previous 2 methods. This event is typically triggered only when multiple histories of the same site have been set by the previous 2 methods and navigated (forward or backward) between them. At the same time, the state object (1th parameter) set by the previous 2 methods will be returned at this time through the return of the event event.state .

Also note that the history.pushState() history.replaceState() event itself is not triggered when it is called popstate . Pop and push are not the same!

How to apply

HTML5 History API is not much content, how to apply it to improve the Ajax page?

First, add support for the URL status parameter on the server side, for example, the ?page=3 contents of the corresponding page number (back-end template) will be output. It can also be the server side of the corresponding page number of the data to JavaScript, JavaScript to the page to write content (front-end template).

Next, use history.pushState() to set the correct URL with parameters at the same time as any page. The code might be like this:

"?page=" + pageNow;history.pushState(null, "", newURL);

In this case, the F5 refresh state restore is resolved.

However, it is not over, click Back in the browser, for example, from the ?page=3 back ?page=2 , you will find that there is no change. According to reason, this time should also correspond to change. It's going to use the popstate event.

For window adding popstate events, add the processing when this navigation changes. The code might be like this (jQuery):

$(window).on("popstate", function(event) { // 取得之前通过pushState保存的state object,尽管本示例并不打算使用它。 // jQuery对event做了一层包装,需要通过originalEvent取得原生event。 var state = event.originalEvent.state, // 本示例直接取URL参数来处理 reg = /page=(\d+)/, regMatch = reg.exec(location.search), // 第1页的时候既可以是 ?page=1,也可以根本没有page参数 pageNow = regMatch === null ? 1 : +regMatch[1]; updateByPage(pageNow);});

So, it's done. Does that seem like a pretty easy thing to do? In browsers that support the HTML5 history API, the above section has been done with Ajax paging with page numbering.

Compatibility issues that need to be considered

Based on the data on Caniuse, ie10+ and other mainstream browsers support the HTML5 history API. To ensure that unsupported browsers do not give an error, you can add support for HTML5 History API judgment:

// 参考自 http://modernizr.com/download/#-history 源码var isHistoryApi = !!(window.history && history.pushState);// ...if(isHistoryApi){ // ...}

In this way, an AJAX page, on the browser that supports the HTML5 history API, will intelligently save the current page number information, while the unsupported browser still works, but does not save the page number information (as it did before the improvement). I think it's best to follow the "progressive enhancement" approach, which is to use less code to optimize the experience of advanced browsers.

If you really want to be consistent in all kinds of browsers, have such a recording function?

It is recommended to use Benjamin Lupton's History.js, which provides an API similar to the HTML5 history API, which can be rolled back to hash in an unsupported browser to process the historical record. Although in order to be compatible with this hash fallback form you may want to do something extra (hash will not be sent to the server side), but it does allow you to achieve a wider range of compatibility.

HTML5 History API is not perfect

Even if you consider only browsers that support the HTML5 history API, there will be differences and problems with some of the details of the HTML5 history API. History.js provides a version of the HTML5 browser only, and still contains a lot of code to handle compatibility issues.

But it doesn't matter if it's not perfect. With my test results, the simple notation presented in this article will work correctly on most browsers that support the HTML5 history API. If you're worried about which browsers have a potential problem, test that browser. Your last self-written code for compatible processing is likely to be much less than a JavaScript library, after all, you don't necessarily like to introduce a JavaScript library to complete a feature.

Some of the relevant content

The hash in the address bar used to be a marker that was used extensively to record the status of a page, so you can read this article about it.

Now that the browser address bar and history can be manipulated without refreshing, can the common link jumps in the same site be transformed into Ajax to enhance the experience? Yes, and already have Pjax, turbolinks these works that specialize in accomplishing this function.

Not just page flipping, the HTML5 history API will be especially useful for single-page applications with lots of Ajax and multiple views.

It is not always appropriate to generate a history for each state of a page (which makes the user's history chaotic), as appropriate, rather replaceState() than pushState() to control the number of historical records.

Conclusion

HTML5 History API Easy to learn, not a few lines of code can do "status record" This small improvement, if you can choose "progressive enhancement", it can really go online!

--------------------------------------------------

HTML4 History API
===================
+ History.length History Entries
+ history.go (n) n can be any forward or backward n step for positive negative numbers
+ History.back (); Back off
+ History.forward (); Forward


HTML5 History API
===================
+ history.pushstate (data, title, [url]); * Add a record to the top of the history stack *
' Data ': passed as a parameter in the callback of the Onpopstate event
' title ': the page title, the browser will ignore this parameter
' URL ': the page address defaults to the current URL
+ history.replacestate (data, title, [url]); * Replace current history, parameter with Pushstate method *
+ history.state * Storage data of the above method, different browser read and write permissions are not the same *
+ window.onpopstate * Response to Pushstate or replacestate calls *

About HTML5 's History API

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.