JavaScript implements simple front-end routing

Source: Internet
Author: User

Http://www.helloweba.com/view-blog-385.html

The concept of web development is not unfamiliar, we are exposed to front-end routing and back-end routing. Back-end routing is an important module in many frameworks, such as the use of routing features in Thinkphp,wordpress, which makes the requested URL address more concise. The same front-end routing is also common in single-page applications, which makes the front-end page experience smoother.

Front-end routing is supported in many open-source JS class library frameworks, such as Angularjs,backbone,reactjs and so on. The principle of front-end routing and back-end routing is to allow all interactions and presentation to run on a single page to reduce server requests and improve the customer experience, and more and more websites, especially Web applications, use front-end routing.

This article uses JavaScript to implement an extremely simple routing instance.

Html

The page has a navigation menu of UL, and a div#result is used to display the results when you click on the navigation menu, #result中会显示不同的结果内容.

<ul>      <Li><ahref="#/">Home</a></Li>      <Li><ahref= "#/product">Products</a></Li>      <Li><ahref= "#/server">Service</a></Li>  </ul> <DivID= "Result"></Div>
Javascript

A brief introduction to the implementation of the front-end routing principle, in the form of hash (also can use the history API to handle) as an example, when the hash of the URL changes, triggering Hashchange registration callback, callback to carry out different operations, different content display.

functionRouter () { This. Routes = {};  This. Cururl = ";  This. Route =function(Path, callback) { This. routes[path] = Callback | |function(){};      };  This. Refresh =function(){          This. Cururl = Location.hash.slice (1) | | ‘/‘;  This. routes[ This. Cururl]     ();      };  This. init =function() {Window.addeventlistener (' Load ', This. Refresh.bind ( This),false); Window.addeventlistener (' Hashchange ', This. Refresh.bind ( This),false); } }

The above code is implemented by the system router object, which mainly provides three methods:

init listens for browser URL hash update events.

the callback to the callback array routes when the route store routing update is in the callback function that will be responsible for updating the page.

Refresh executes the callback function corresponding to the current URL and updates the page.

Router is called as follows: Click on the trigger URL to change the hash, and update the content accordingly, you will find each time you click on the menu, #result中会变换背景色和内容.

varR =NewRouter (); R.init (); varres = document.getElementById (' result '); R.route (‘/‘,function() {Res.style.background= ' Blue '; Res.innerhtml= ' This is the homepage ';  }); R.route ('/product ',function() {Res.style.background= ' Orange '; Res.innerhtml= ' This is the product page ';  }); R.route ('/server ',function() {Res.style.background= ' Black '; Res.innerhtml= ' This is the Service page '; });

The above is a simple implementation of a front-end routing, in the actual application, the hash should be processed in a regular matching to meet the application of a large number of URLs, while increasing the Ajax asynchronous request page content and other functions. Although this example is very simple, but in fact many routing systems are rooted in this, the other routing system is mainly for their own use of the framework mechanism for matching and optimization.

<!DOCTYPE HTML><HTMLLang= "ZH-CN"><Head>    <MetaCharSet= "Utf-8">    <title></title></Head><Body>    <ul>        <Li><aonclick= "location.href= ' #/'">Home</a></Li>        <Li><ahref= "#/product">Products</a></Li>        <Li><aonclick= "location.href= ' #/server '">Service</a></Li>    </ul>    <DivID= "Result"></Div>    <Scripttype= "Text/javascript">Console.log (Date.now ()); /** * in hash form (can also use the history API to handle) as an example, when the hash of the URL changes, triggering Hashchange registration callback, callback to do different operations, to display different content. */        functionRouter () { This. Routers= {};  This. Cururl= "';  This. Route= function(Path, callback) { This. Routers[path]=Callback|| function(){};            };  This. Refresh= function() {console.log (Location.hash);  This. Cururl=Location.hash.slice (1) || '/';  This. routers[ This. Cururl]            (); }             This. Init= function() {Window.addeventlistener ('Load',  This. Refresh.bind ( This), false); Window.addeventlistener ('Hashchange',  This. Refresh.bind ( This), false); }        }        varR= NewRouter ();        R.init (); varRes=document.getElementById ('result'); R.route ('/',function() {Res.style.background= 'Blue'; Res.innerhtml= 'This is the homepage';        }); R.route ('/product',function() {Res.style.background= 'Orange'; Res.innerhtml= 'This is the product page';        }); R.route ('/server',function() {Res.style.background= 'Black'; Res.innerhtml= 'This is the service page';    }); </Script></Body></HTML>

JavaScript implements simple front-end routing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.