js implements simple front-end routing -- hash method

In a single page application (SPA), the front end renders different pages by changing the url, but the page of the url is expected to be recorded. This allows you to use the browser's back and forward keys to return to the previous page.

To achieve this, first implement front-end routing. Depending on the route, different pages are rendered and different methods are executed.

There are two ways to implement simple front-end routing:

1. hash

2.history API

//------------------------------------------------------------------------------------------------

The first method of hashing is described below.

This method is mainly implemented by listening to the onhashchange event, but there are browser compatibility issues. Here's what the browser supports (screenshot source: http://www.runoob.com/jsref/event-onhashchange.html ).


In browsers that do not support this event, this can be achieved by polling for changes in the hash.

The following is a small demo that implements a simple front-end routing function.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .content{
            position:absolute;
            left: 0px;
            top:0px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="index-page" class="content">
        <ul>
            <li><a href="#/index">index</a></li>
            <li><a href="#/text">text</a></li>
            <li><a href="#/news">news</a></li>
            <li><a href="#/about">about</a></li>
            <li><a href="http://www.baidu.com">baidu</a></li>
        </ul>
    </div>
    <div id="text-page" class="content">
        <h1> this is text page</h1>
        <a href="#/index">back</a>
    </div>
    <div id="news-page" class="content">
        <h1>this is new page</h1>
        <a href="#/index">back</a>
    </div>
    <div id="about-page" class="content">
        <h1>this is about page</h1>
        <a href="#/index">back</a>
    </div>
    <script>
        //Constructor
        function Router(){
            this.routes={};
            this.currentURL='';
        }
        //Define the routing callback function
        Router.prototype.route = function(path,callback){
            this.routes[path] = callback || function(){};
        }
        //Define the calling function when the route is updated
        Router.prototype.refresh = function(){
            this.currentURL = location.hash.slice(1) || '/index';
            try { //throws incorrect route
                this.routes[this.currentURL]();
            }
            catch(err) {
                alert("Please enter a valid route");
            }
        }
        //Route initialization function, add listener events
        Router.prototype.init = function () {
            var that = this;
            if (window.addEventListener) {
                window.addEventListener("load",function(){that.refresh();},false);
                if ( "onhashchange" in window.document.body ) {
                    window.addEventListener("hashchange",function(){that.refresh();},false)  
                }else{
                    onhashchange_compatibility(that);
                }
            } else if (window.attachEvent) { //ie compatible with lower versions
                window.attachEvent("onload",function(){that.refresh();},false);
                window.attachEvent("onhashchange",function(){that.refresh();},false)
                onhashchange_compatibility(that);
            }  
            //bind() function is not supported below IE8
            // window.addEventListener('load',this.refresh.bind(this),false);
            // window.addEventListener('hashchange',this.refresh.bind(this),false);
        }

        // poll for url changes
        function onhashchange_compatibility(that){
            var location = window.location,
            oldURL = location.href,
            oldHash = location.hash;
            // Check whether the hash has changed every 100ms
            setInterval(function() {
                var newHash = location.hash;
                if ( newHash != oldHash) {
                    that.refresh();
                    oldURL = location.href;
                    oldHash = newHash;
                }
            }, 100);
        }

        //The callback function when the custom route is updated
        function display_page(id){
            var el = document.getElementsByClassName("content");
            for(var i = 0; i < el.length; i++){
                el[i].style.display = "none";
            }         
            el[id].style.display = "block";
        }
         
        window.Router = new Router();
        //Write legal routes and executed callback functions to routes
        Router.route('/index',function(){
            display_page(0);
        })
        Router.route('/text',function(){
            display_page(1);
        })
        Router.route('/news',function(){
            display_page(2);
        })         
        Router.route('/about',function(){
            display_page(3);
        })
        //initialization
        window.Router.init();
    </script>
</body>
</html>

// chatter----------------------------------------------- ------------------------------------

These are my study notes. I refer to the code written in the blog post on the Internet. The URL cannot be found, so I didn't post it.

Every time you dig a hole, you will find that it is super deep inside. If you are a beginner, please give more advice.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324953607&siteId=291194637