search
HomeWeb Front-endH5 TutorialThe impact of History API in h5 on web applications

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);

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
}

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>

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>

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
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
H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.