前端路由筆記
前端路由的實現本質:檢測URL變化,獲取url地址,解析url匹配頁面;
檢測URL變化有兩種方式: hash,HTML5 History
-
HTML5 History
history.pushState 和 history.replaceState這兩個api都分別接收三個引數:狀態物件,標題, url (此url地址不支援跨域,跨域會報錯)
這兩個API都會操作瀏覽器的歷史記錄,並不引起瀏覽器的重新整理,pushState會增加一條新的歷史記錄,replaceState會替換當前的歷史記錄;
popstate事件,需要注意的是呼叫history.pushState()或history.replaceState()不會觸發popstate事件。只有在做出瀏覽器動作時,才會觸發該事件,如使用者點選瀏覽器的回退按鈕,或者在Javascript程式碼中呼叫3.back()。
原理在點選某個路由時執行pushState,在操作瀏覽器時執行popstate; -
hashlocation.hash
window.location修改hash至不會引起頁面重新整理,而是當作新頁面加到歷史記錄中。hash值變化會觸發hashchange事件。
Function Router(){ this.currentUrl = ''; this.routes = {}; } Router.prototype.route = function(url, callback){ this.routes[url] = callback || function(){} } Router.prototype.refresh = function(){ this.currentUrl = location.hash.slice(1) || '/'; this.routes[this.currentUrl](); } Router.prototype.init = function(){ window.addEventListener('load', this.refresh.bind(this), false); window.addEventListener('hashchange', this.refresh.bind(this), false); } //使用 var $target = $('#target'); var route = new Router(); route.init(); route.route('/', $target.html('this is index page!!') ); route.route('/page1', $target.html('this is page1!!'));