http://www.helloweba.com/view-blog-385.html
WEB開發中路由概念並不陌生,我們接觸到的有前端路由和后端路由。后端路由在很多框架中是一個重要的模塊,如Thinkphp,Wordpress中都應用了路由功能,它能夠讓請求的url地址變得更簡潔。同樣前端路由在單頁面應用也很常見,它使得前端頁面體驗更流暢。
前端路由在很多開源的js類庫框架中都得到支持,如angularJS,Backbone,Reactjs等等。前端路由和后端路由原理一樣,是讓所有的交互和展現在一個頁面運行以達到減少服務器請求,提高客戶體驗的目的,越來越多的網站特別是web應用都用到了前端路由。
本文將使用javascript實現一個極其簡單的路由實例。
HTML
頁面中有一個導航菜單ul,和一個div#result用來顯示結果,當點擊導航菜單時,#result中會顯示不同的結果內容。
<ul> <li><a href="#/">首頁</a></li> <li><a href="#/product">產品</a></li> <li><a href="#/server">服務</a></li> </ul> <div id="result"></div>
JAVASCRIPT
說一下前端路由實現的簡要原理,以 hash 形式(也可以使用 History API 來處理)為例,當 url 的 hash 發生變化時,觸發 hashchange 注冊的回調,回調中去進行不同的操作,進行不同的內容的展示。
function Router(){ 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); } }
上面代碼中路由系統Router對象實現,主要提供三個方法:
init 監聽瀏覽器 url hash 更新事件。
route 存儲路由更新時的回調到回調數組routes中,回調函數將負責對頁面的更新。
refresh 執行當前url對應的回調函數,更新頁面。
Router調用方式如下:點擊觸發 url 的 hash 改變,並對應地更新內容,運行后你會發現每次點擊菜單時,#result中會變換背景色和內容。
var R = new Router(); R.init(); var res = document.getElementById('result'); R.route('/', function() { res.style.background = 'blue'; res.innerHTML = '這是首頁'; }); R.route('/product', function() { res.style.background = 'orange'; res.innerHTML = '這是產品頁'; }); R.route('/server', function() { res.style.background = 'black'; res.innerHTML = '這是服務頁'; });
以上為一個前端路由的簡單實現,實際應用中,應該對hash進行正則匹配處理,以滿足大量url的應用,同時增加ajax異步請求頁面內容等功能。雖然這個實例非常簡單,但實際上很多路由系統的根基都立於此,其他路由系統主要是對自身使用的框架機制進行配套及優化。
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title></title> </head> <body> <ul> <li><a onclick="location.href='#/'">首頁</a></li> <li><a href="#/product">產品</a></li> <li><a onclick="location.href='#/server'">服務</a></li> </ul> <div id="result"></div> <script type="text/javascript"> console.log(Date.now()); /** * 以 hash 形式(也可以使用 History API 來處理)為例,當 url 的 hash 發生變化時,觸發 hashchange 注冊的回調,回調中去進行不同的操作,進行不同的內容的展示。 */ function Router(){ 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); } } var R = new Router(); R.init(); var res = document.getElementById('result'); R.route('/',function(){ res.style.background = 'blue'; res.innerHTML = '這是首頁'; }); R.route('/product',function(){ res.style.background = 'orange'; res.innerHTML = '這是產品頁'; }); R.route('/server',function(){ res.style.background = 'black'; res.innerHTML = '這是服務頁'; }); </script> </body> </html>