Home  >  Article  >  Web Front-end  >  html5 History API implements updating address bar URL without refreshing

html5 History API implements updating address bar URL without refreshing

伊谢尔伦
伊谢尔伦Original
2016-11-23 14:44:382452browse

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

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

Why introduce History API?

In this article, we will understand the origin of History API in HTML 5. Before this, we often used hash values ​​to alter page content, especially those that were particularly important to the page. Because there is no refresh, it is impossible to change the URL of a single-page application. Additionally, when you change the hash value of a URL, it has no effect on the browser's history.

Now, for the History API of HTML 5, these are all easily implementable, but since there is no need to use hash values ​​for single-page applications, it may require additional development scripts. It also allows us to build new applications in an SEO-friendly way. Additionally, it reduces bandwidth, but how to prove it?

In this article, I will use History API to develop a single-page application to prove the above problems.

This also means that I have to load the necessary resources on the homepage first. From now on, the page only loads the required content. In other words, the application does not load all the content at the beginning. It will be loaded when the second application content is requested.

Note that you need to perform some server-side coding to serve only partial resources, rather than the complete page content.

Browser support

At the time of writing this article, the support for History API by major browsers is very good. You can click here to check its support. This link will tell you the supported browsers and use Previously, it was always good practice to detect which specific features were supported.

In order to determine whether the browser supports this API by changing the method, you can use the following line of code to check:

return !!(window.history && history.pushState);

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

if (Modernizr.history) {
    // History API Supported
}

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

Using History

HTML 5 provides two new methods:

1.history.pushState();
2.history.replaceState();

Both methods allow us to add and update history records, their Works the same and can add the same number of parameters. In addition to methods, there is also the popstate event. In the following article, we will introduce how to use and when to use the popstate event.

pushState() has the same parameters as replaceState(). The parameter description is as follows:

state: stores a JSON string and can be used in the popstate event.

title: Most browsers now do not support or ignore this parameter. It is best to use null instead.

url: Any valid URL, used to update the browser's address bar, and does not care whether the URL already exists in the address list. What's more, it doesn't reload the page.

The main difference between the two methods is: pushState() adds a new entry to the history stack, and replaceState() replaces the current record value. If you are still confused about this, use some examples to demonstrate the difference.

Suppose we have two stack blocks, one labeled 1 and the other labeled 2, and you have a third stack block labeled 3. When pushState() is executed, stack block 3 will be added to the existing stack, so the stack will have 3 block stacks.

Under the same hypothetical scenario, when replaceState() is executed, block 3 will be placed on the stack of block 2. Therefore, the number of history records remains unchanged, that is to say, pushState() will increase the number of history by 1. The comparison result is as follows:

html5 History API implements updating address bar URL without refreshing

At this point, in order to control the browser’s history, we The pushState() and replaceState() events are ignored. But assuming the browser counts a lot of bad records, the user may be redirected to these pages, or maybe not. In this case, unexpected problems arise when users use the browser's forward and back navigation buttons.

Although when we use pushState() and replaceState() for processing, expect the popstate event to be triggered. But in reality, this is not the case. In contrast, when you browse the session history, whether you click the forward or back buttons, or use the history.go and history.back methods, popstate will be triggered.

注意:在WebKit浏览器中,popstate事件在document的onload事件后触发,Firefox和IE没有这种行为。

Demo示例

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 Links above to see 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(&#39;document&#39;).ready(function(){
        jQuery(&#39;.historyAPI&#39;).on(&#39;click&#39;, function(e){
            e.preventDefault();
            var href = $(this).attr(&#39;href&#39;);
            // Getting Content
            getContent(href, true);
            jQuery(&#39;.historyAPI&#39;).removeClass(&#39;active&#39;);
            $(this).addClass(&#39;active&#39;);
        });
    });
    // Adding popstate event listener to handle browser back button 
    window.addEventListener("popstate", function(e) {
        // Get State value using e.state
        getContent(location.pathname, false);
    });
    function getContent(url, addEntry) {
        $.get(url)
        .done(function( data ) {
            // Updating Content on Page
            $(&#39;#contentHolder&#39;).html(data);
            if(addEntry == true) {
                // Add History Entry using pushState
                history.pushState(null, null, url);
            }
        });
    }
</script>

HTML 5中的History API 对Web应用有着很大的影响。为了更容易的创建有效率的、对SEO友好的单页面应用,它移除了对散列值的依赖。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn