Home Web Front-end H5 Tutorial Detailed explanation of History mode in HTML5

Detailed explanation of History mode in HTML5

Jul 18, 2017 pm 01:51 PM
h5 history html5

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

1. history.pushState


history.pushState(state, title, url);
Copy after login

The first and second parameters above can be empty, mainly the third one Parameter, indicating the address of the new historical 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 one. URL

2. history.replaceState


history.replaceState(state, title, url);
Copy after login

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

3. window.onpopstate

to monitor changes in url


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

//或者
window.onpopstate = function(){}
Copy after login

javascript script executes window.history .pushState and window.history.replaceState will not trigger the onpopstate event. Clicking forward or backward in the browser will trigger it.

The reactions of Google Chrome and Firefox are different when the page is first opened. Google Chrome The strange thing is that the browser triggers the onpopstate event, but the Firefox browser does not

4. Below is an example of an HTML5 mode similar to vue-router, purely to deepen understanding, and the writing is very rough.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5 History 模式(第二版)</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <style type="text/css">
        .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>
</head>
<body>
    <p class="container-bg">
        <ul class="pagination">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <ul class="ptting"></ul>
    </p>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
    
    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;</li>&#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;</li>&#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>
</body>
</html>
Copy after login

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


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

app.use(router)

app.listen(3000)
Copy after login

 注意:history.pushState({pageIndex : 1}, "", "http://127.0.0.1:3000/lmw/"+query)这里第三个参数写了完整的绝对路径,如果写成"/lmw/"+query这样的相对路径,会随着query值得增加无限在url后面追加,因为相对路径它一定是相对于当前的URL
Copy after login

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles