路由就是根據不一樣的 url 地址展現不一樣的內容或頁面,早期路由的概念是在後端出現的,經過服務器端渲染後返回頁面,隨着頁面愈來愈複雜,服務器端壓力愈來愈大。後來ajax異步刷新的出現使得前端也能夠對url進行管理,此時,前端路由就出現了。html
單頁面就是有前端路由來實現的,也就是說網站只有一個頁面,點擊導航會顯示不一樣的內容,對應的url也在發生改變。在這個過程當中,js會實時檢測url的變化,從而改變顯示的內容。前端
全過程只改變內容,不刷新頁面。jquery
index.htmlweb
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>前端路由測試</title> <script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script> <style> *{ margin:0; padding: 0; } .content{ width: 500px; height: 300px; margin-top: 30px; margin:20px auto 0; } #click_btn{ width: 500px; height: 50px; margin:100px auto 0; } #click_btn a{ display: block; background: #333; color: #fff; text-decoration: none; line-height: 50px; text-align: center; float: left; margin-right: 15px; padding: 0px 15px; } #click_btn a:hover{ background: #666; } </style> </head> <body> <div id="click_btn"> <a href="#/one">第一個頁面</a> <a href="#/two">第二個頁面</a> <a href="#/three">第三個頁面</a> </div> <div class="content"></div> <script src="router.js"></script> <script src="test.js"></script> </body> </html>
router.jsajax
//構造函數 function Router() { this.routes = {}; this.currentUrl = ''; } Router.prototype.route = function(path, callback) { this.routes[path] = callback || function(){};//給不一樣的hash設置不一樣的回調函數 }; Router.prototype.refresh = function() { console.log(location.hash.slice(1));//獲取到相應的hash值 this.currentUrl = location.hash.slice(1) || '/';//若是存在hash值則獲取到,不然設置hash值爲/ // console.log(this.currentUrl); if(this.currentUrl&&this.currentUrl!='/'){ this.routes[this.currentUrl]();//根據當前的hash值來調用相對應的回調函數 } }; Router.prototype.init = function() { window.addEventListener('load', this.refresh.bind(this), false); window.addEventListener('hashchange', this.refresh.bind(this), false); } //給window對象掛載屬性 window.Router = new Router(); window.Router.init();
test.js後端
Router.route('/one', function () { $(".content").html("<p>路由就是根據不一樣的 url 地址展現不一樣的內容或頁面,早期路由的概念是在後端出現的,經過服務器端渲染後返回頁面,隨着頁面愈來愈複雜,服務器端壓力愈來愈大。後來ajax異步刷新的出現使得前端也能夠對url進行管理,此時,前端路由就出現了。</p>"); }); Router.route('/two', function () { $(".content").html("<h3>單頁面就是有前端路由來實現的,也就是說網站只有一個頁面,點擊導航會顯示不一樣的內容,對應的url也在發生改變。在這個過程當中,js會實時檢測url的變化,從而改變顯示的內容。</h3>"); }); Router.route('/three', function () { $(".content").html("<img src='https://upload-images.jianshu.io/upload_images/12890819-f8665293cc8d0dcf.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp' width='500'/>"); });
原文:JS是如何實現前端路由的服務器