Table of Contents
Home!
Home Web Front-end H5 Tutorial The impact of History API in h5 on web applications

The impact of History API in h5 on web applications

May 18, 2017 am 10:46 AM

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 HTML 5's History API, these are all easily implementable, but since single-page applications don't necessarily need to use hash values, 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 the 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 only serve part of the resource, 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 view its support status. This link will tell Before you support a browser and use it, it's always good practice to detect support for specific features.

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);
Copy after login

In addition, I recommend referring to this article: Detect Support for Various HTML5 Features.(ps: will be translated later)

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

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

If you Your browser does not support 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, they work 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:

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

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

3. url: any valid URL, used for Updates the browser's address bar, regardless of 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 marked 1 and the other marked 2, and you have a third stack block marked 3. When pushState() is executed, stack block 3 will be added to the existing stack, so the stack will have 3 block stacks.

同样的假设情景下,当执行replaceState()时,将在块2的堆栈和放置块3。所以history的记录条数不变,也就是说,pushState()会让history的数量加1.

比较结果如下图:

The impact of History API in h5 on web applications

到此,为了控制浏览器的历史记录,我们忽略了pushState()和replaceState()的事件。但是假设浏览器统计了许多的不良记录,用户可能会被重定向到这些页面,或许也不会。在这种情况下,当用户使用浏览器的前进和后退导航按钮时就会产生意外的问题。

尽管当我们使用pushState()和replaceState()进行处理时,期待popstate事件被触发。但实际上,情况并不是这样。相反,当你浏览会话历史记录时,不管你是点击前进或者后退按钮,还是使用history.go和history.back方法,popstate都会被触发。

In WebKit browsers, a popstate event would be triggered after document’s onload event, but Firefox and IE do not have this behavior.(在WebKit浏览器中,popstate事件在document的onload事件后触发,Firefox和IE没有这种行为)。

Demo示例

HTML:

<p class="container">
    <p 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>
    </p>
    <p class="row">
        <p class="col-md-6">
            <p class="well">
                Click on Links above to see history API usage using <code>pushState</code> method.
            </p>
        </p>
        <p class="row">  
            <p class="jumbotron" id="contentHolder">
                <h1 id="Home">Home!</h1>
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
            </p>
        </p>
    </p>
</p>
Copy after login

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>
Copy after login

Demo 1:HTML 5 History API – pushState

历史条目在浏览器中被计算,并且可以很容易的使用浏览器的前进和后退按钮。View Demo  (ps:你在点击demo1的选项卡时,其记录会被添加到浏览器的历史记录,当点击后退/前进按钮时,可以回到/跳到你之前点击的选项卡对应的页面)

Demo 2:HTML 5 History API – replaceState

历史条目在浏览器中被更新,并且不能使用浏览器的前进和后退按钮进行浏览。View Demo  (ps:你在点击demo1的选项卡时,其记录会被替换当前浏览器的历史记录,当点击后退/前进按钮时,不可以回到/跳到你之前点击的选项卡对应的页面,而是返回/跳到你进入demo2的上一个页面)

总结(ps:喜欢这两个字~~~^_^~~~)

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

【相关推荐】

1. 特别推荐“php程序员工具箱”V0.1版本下载

2. js中的window.history的用法(一)

3. js中的window.history的用法(二)

4. 深入了解h5中history特性--pushState、replaceState

5. 详细介绍h5中的history.pushState()使用实例

The above is the detailed content of The impact of History API in h5 on web applications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does h5 mean? What does h5 mean? Aug 02, 2023 pm 01:52 PM

H5 refers to HTML5, the latest version of HTML. H5 is a powerful markup language that provides developers with more choices and creative space. Its emergence promotes the development of Web technology, making the interaction and effect of web pages more Excellent, as H5 technology gradually matures and becomes popular, I believe it will play an increasingly important role in the Internet world.

How to use Nginx web server caddy How to use Nginx web server caddy May 30, 2023 pm 12:19 PM

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

How to configure nginx to ensure that the frps server and web share port 80 How to configure nginx to ensure that the frps server and web share port 80 Jun 03, 2023 am 08:19 AM

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

See all articles