Enhanced Ajax experience with new features of HTML5 history (GO)

Source: Internet
Author: User

I. Scene reproduction

As you know, Ajax can achieve a page without refreshing operation, but will cause two and normal page operation (there is a refresh page change) has a significant difference--url not modified and can not use the forward, Back button. For example, the common Ajax paging, on the first page click on the second page of the link, the Ajax page after the completion of the browser address bar is still the URL of the first page, using the Back button can not go back to the first page. The change of URL represents an identity, in the traditional Web experience, the change of content with the change of the URL, the change of the URL, the forward and the Back button to form a unique navigation experience, and Ajax destruction of this experience will inevitably cause inconvenience to users.

Of course, very early on, the wit front-end engineers have been thinking about the solution, the most common is to use hash--at the end of the URL to add a shape such as "#xxx" of the logo, and then use Onhashchange and other ways to listen to the hash value changes to make corresponding processing.

Very troublesome? Yes, so there are a couple of new features in HTML5 history that can be elegantly addressed to these issues!

Two. New features of HTML5 history

The history object was introduced from HTML4, and the HTML5 added Pushstate, replacestate two methods, and Popstate events. Here are some simple introductions.

1. Pushstate () method

The function of Pushstate () is to press a record into the history stack, which has three parameters:

State object--An object that holds the status information, and when the Popstate event is triggered, a Popstate event object that contains a copy of the corresponding States object. The state object has a small capacity (640k is mandatory in Firefox), and it is recommended to use Localstorage or sessionstorage if you need to store large data.

title--is the title of the page that is pressed into the history, which is temporarily ignored by all browsers, and can be used to fill in the blanks or a short title in the actual development.

url--the address of the new history, either a relative path or an absolute path, or the current URL as the base location for the relative path.

2. Replacestate () method

The Replacestate () method is similar to the Pushstate () method, and the parameter is the same as pushstate (), but the Replacestate () method modifies the current history instead of creating a new record, so the state that needs to update the current history Object or URL, it is more appropriate to use this method.

3. Popstate Events

The Popstate event is triggered on the Window object when the active history changes (such as forward, backward, call pushstate, or Replacestate method). As described above, if the active history is created by Pushstate or modified by replacestate, then the State property of the Popstate event will contain a copy of the corresponding States object, and developers can call these in the popstate callback before saving The information in the state object.

It's important to note that Chrome generates Popstate events when opening pages (including the first open page) and page refreshes, but Firefox does not, which can be a problem for development, but here's a solution.

4. Browser compatible
features Chrome Firefox (Gecko) Internet Explorer Opera Safari
Pushstate, Replacestate 5 4.0 (2.0) 10 11.50 5.0
History.state 18 4.0 (2.0) 10 11.50 6.0
Three. Enhance the Ajax experience with new features of history

The enhancement experience here is essentially about solving the two issues mentioned at the beginning of the article--ajax the URL is not modified and the forward and backward functions are not valid when you turn the page.

Look at the above method, I believe you can think of the basic solution, is nothing more than when the Ajax requirements pushstate a record to the history, and then in the Popstate callback function to make corresponding processing. Of course, in order to actually get a better experience, the content to be done is more complicated. The following is an example of Ajax paging, providing a complete idea:

    • Each time you use Ajax to get a new page, use Pushstate () to press the URL of the new page into the top of the history stack.
    • Listen for popstate events, when the user forward or backward in the callback based on the forward or backward URL back to use Ajax to get the page content, Ajax forward and backward.
    • Chrome creates a Popstate event when the page is opened and the page is refreshed, resulting in unwanted AJAX requests, so you need to use the URL in popstate to determine whether the user is clicking Forward or backward, or to open or refresh the page, triggering Ajax to get the corresponding Content.

Basic code

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 // 定义 Ajax 获取分页方法,这里不列出具体内容function turnPage(url){    // ...}// 定义 popstate 的回调if( history.pushState ){ // 判断浏览器是否支持 pushState    // currentState 用于记录 popstate 产生前的页面 url,页面加载时初始化 currentState 为当前链接    var currentState = window.location.href;    window.addEventListener(‘popstate‘, function(event){                // _currentUrl 用于记录 popstate 产生时的页面 url        var _currentUrl = window.location.href;                /* 判断 currentState 和 _currentUrl 是否相同,         * 若相同则表明这个 popstate 产生前后页面 url 没有变化,         * 即页面是第一次加载页面或者被刷新,无需触发新的 Ajax 请求,         * 若不同则表明 url 已改变,这是触发 Ajax 获取内容         */        if( currentState != _currentUrl ){                     console.log(‘获取新分页‘);                            turnPage(_currentUrl); // 根据当前 url 重新获取分页内容                        currentState = _currentUrl; // 更新 currentState                }      });}// 绑定点击分页产生 Ajax 请求// 点击分页链接,获取 url 为 currentLink,产生一次 Ajax 请求turnPage(currentLink); // 调用 pushState() 压入新记录if( history.pushState ){ // 判断浏览器是否支持 pushState    // 往历史记录中压入新记录,浏览器的地址栏上的 url 同时会被修改为新 url    history.pushState(null, document.title, currentLink);            currentState = window.location.href; // 分页时更新 currentState 为当前 url}

This site has been based on the above ideas for the Ajax page enhancements, the specific situation is as follows:

Open page, URL displays the URL of the first page

Click on the second page link, trigger Ajax paging, in Ajax call Pushstate (), you can see that the URL has been modified to the second page of the URL

Click the Back button, the URL address becomes the first page, and then trigger Ajax in the popstate callback to get the contents of the first page.

This makes it possible to absorb both the benefits of a partial refresh page while preserving the traditional URL navigation experience. For browsers that do not support pushstate, these browsers can be ignored using progressive enhancement design, which is a feature of enhanced experience, but if you have to take care of those browsers, you can use a hash scheme instead.

Four. Existing Solutions

If you need a direct solution, you can refer to this package and implement a cross-browser compatible library--history.js

This article was published by Kayo Lee, this article link: http://kayosite.com/html5-history-improve-ajax.html

Enhanced Ajax experience with new features of HTML5 history (GO)

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.