search
HomeWeb Front-endH5 TutorialDetailed explanation of the use of History mode in H5

Detailed explanation of the use of History mode in H5

Mar 26, 2018 pm 04:47 PM
historyhtml5Detailed explanation

This time I will bring you a detailed explanation of the use of the History mode in H5. What are the precautions when using the History mode in H5. The following is a practical case, let's take a look.

I recently saw the implementation of vue-router's HTML5 History mode routing, and then I went to study the history of HTML5. Here are some of my understandings. By the way, I used jquery to write an implementation similar to the HTML5 in vue-router. History mode router to achieve the purpose of practicing and becoming familiar with it.

1. history.pushState

history.pushState(state, title, url);

The first and second parameters above can be empty, mainly the third parameter, which means The address of the new history record. The browser will not load this URL after calling the pushState() method. The new URL does not have to be an absolute address. If it is relative, it must be relative to the current URL

2. history.replaceState

history.replaceState(state, title, url);

window.history.replaceState is similar to window.history.pushState, the difference is that replaceState will not be in window.history The effect of adding a new historical record point is similar to window.location.replace(url), which will not add a new record point to the historical record point.

3. window.onpopstate

to monitor url changes

window.addEventListener("popstate", function() {
    var currentState = history.state;
    /*
     * 触发事件后要执行的程序
    */                                            
});
//或者
window.onpopstate = function(){}

javascriptScript execution window.history.pushState and window.history.replaceState will not trigger the onpopstate event. Clicking forward or backward in the browser will trigger

Google Chrome and Firefox for the first time on the page. The opening response is different. Google Chrome strangely triggers the onpopstate event, but Firefox does not.

4. Post an HTML5 mode similar to vue-router below. The examples are purely for deepening understanding, but the writing is very rough.

nbsp;html>


    <meta>
    <title>HTML5 History 模式(第二版)</title>
    <link>
    <style>
        .container-bg{width:1000px; overflow: hidden; margin-right: 0 auto;}
        .pagination{width: 1000px; background-color: #d8d8d8; height: 30px; line-height: 30px;}
        .pagination li{width: 100px; height: 30px; background: red; float: left; cursor: pointer; color:#fff; margin: 0 10px 0 0;}
    </style>


    <p>
        </p>
                
  • 1
  •             
  • 2
  •             
  • 3
  •         
        
             <script></script>     <script> history.replaceState(null, "页面标题", "http://127.0.0.1:3000/lmw/0");//当页面载入时候,把url地址修改 var searchObject = {};/*此对象用来保存下面pushState的URL作为key值,ajax要查询的ID为val *例如:searchObject = {"http://127.0.0.1:3000/lmw/0":0}*/ var factory = function(){ var addva = document.location.href;//获取完整URL var query = searchObject[addva];//找到该URL对应的值 query = (query == undefined ? 0 :query); //发起ajax加载页面 $.get("/page?page="+query,function(data){ var data2 = JSON.parse(data); var ele = "" for(var i=0;i<data2.data.length;i++){ ele += &#39;<li>&#39;+data2.data[i].name+&#39;&#39; } $(&#39;.ptting&#39;).html(ele) }) }; //点击分页切换事件 $(".pagination li").click(function(){ var query=$(this).index(); $.get("/page?page="+query,function(data){ var data2 = JSON.parse(data); var ele = "" for(var i=0;i<data2.data.length;i++){ ele += &#39;<li>&#39;+data2.data[i].name+&#39;&#39; } $(&#39;.ptting&#39;).html(ele) history.pushState({pageIndex : 1}, "", "http://127.0.0.1:3000/lmw/"+query); //把当前pushState的url,和ajax查询的值存入对象,以供触发pushState事件的时候使用 searchObject["http://127.0.0.1:3000/lmw/"+query] = query }) }) //浏览器前进或者后退的时候触发popstate事件 if (history.pushState) { window.addEventListener("popstate", function() { factory() }); factory() }; </script>

    By the way, I will post a server code in node.js. For testing, I simply wrote one

    var fs = require('fs')
    var path = require('path')
    var express = require('express')
    var app = express();
    app.use(express.static('./public'));
    var router = express.Router();
    router.get('/page',function(req,res){
        var page = req.query.page
        try{
            var text = fs.readFileSync('./data'+page+'.json');
            res.json(text.toString())
        }catch(err){
            res.send('哈哈!傻逼,没有拉!')    
        }
    })
    app.use(router)
    app.listen(3000)

    Note: history.pushState({pageIndex: 1}, "", "http://127.0.0.1:3000/lmw/"+query) The third parameter here writes the complete absolute path. If it is written as a relative path like "/lmw/"+query, it will As the query value increases, it is appended after the url indefinitely, because the relative path must be relative to the current URL
    The server puts data0.json, data1.json, and data2.json to simulate the database fetching data. The server is more The index value (0/1/2) sent from the front end is used to match the read data*.json file and then sent to the front end.

    I believe you have mastered the method after reading the case in this article. Please pay attention for more exciting information. Other related articles on php Chinese website!

    Recommended reading:

    H5 file asynchronous upload

    Dynamic matching of datalist input box and background database data


    The above is the detailed content of Detailed explanation of the use of History mode in H5. 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
    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.

    H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

    H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

    H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

    HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

    HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

    The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

    H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

    H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

    The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

    H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

    The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

    Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

    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

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    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.

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use