JS單頁面應用實現前端路由(hash)
背景介紹
用了許多前端框架來做spa應用,比如說backbone,angular,vue他們都有各自的路由系統,管理著前端的每一個頁面切換,想要理解其中路由的實現,最好的方法就是手動實現一個。
前端路由有2種實現方式,一種是html5推出的historyapi,我們這裡說的是另一種hash路由,就是常見的 # 號,這種方式相容性更好。
需求分析
我們這裡只是簡單的實現一個路由輪子,基本的功能包含以下:
切換頁面
非同步載入js
非同步傳參
實現步驟
1.切換頁面:路由的最大作用就是切換頁面,以往後臺的路由是直接改變了頁面的url方式促使頁面重新整理。但是前端路由通過 # 號不能重新整理頁面,只能通過 window 的監聽事件 hashchange 來監聽hash的變化,然後捕獲到具體的hash值進行操作
//路由切換
window.addEventListener('hashchange',function(){
//do something
this.hashChange()
})
2.註冊路由:我們需要把路由規則註冊到頁面,這樣頁面在切換的時候才會有不同的效果。
//註冊函式
map:function(path,callback){
path = path.replace(/\s*/g,"");//過濾空格
//在有回撥,且回撥是一個正確的函式的情況下進行儲存 以 /name 為key的物件 {callback:xx}
if(callback && Object .prototype.toString.call(callback) === '[object Function]' ){
this.routers[path] ={
callback:callback,//回撥
fn:null //儲存非同步檔案狀態,用來記錄非同步的js檔案是否下載,下文有提及
}
}else{
//打印出錯的堆疊資訊
console.trace('註冊'+path+'地址需要提供正確的的註冊回撥')
}
}
//呼叫方式
map('/detail',function (transition){
...
})
3.非同步載入js:一般單頁面應用為了效能優化,都會把各個頁面的檔案拆分開,按需載入,所以路由裡面要加入非同步載入js檔案的功能。非同步載入我們就採用最簡單的原生方法,建立script標籤,動態引入js。
var _body= document.getElementsByTagName('body')[0],
scriptEle= document.createElement('script');
scriptEle.type= 'text/javascript';
scriptEle.src= xxx.js;
scriptEle.async = true;
scriptEle.onload= function(callback){
//為了避免重複引入js,我們需要在這裡記錄一下已經載入過的檔案,對應的 fn需要賦值處理
callback()
}
_body.appendChild(scriptEle);
4.引數傳遞:在我們動態引入單獨模組的js之後,我們可能需要給這個模組傳遞一些單獨的引數。這裡借鑑了一下jsonp的處理方式,我們把單獨模組的js包裝成一個函式,提供一個全域性的回撥方法,載入完成時候再呼叫回撥函式。
SPA_RESOLVE_INIT = function(transition) {
document.getElementById("content").innerHTML = '<p style="color:#F8C545;">當前非同步渲染列表頁'+ JSON.stringify(transition) +'</p>'
console.log("首頁回撥" + JSON.stringify(transition))
}
擴充套件:以上我們已經完成了基本功能,我們再對齊進行擴充套件,在頁面切換之前beforeEach和切換完成afterEach的時候增加2個方法進行處理。思路是,註冊了這2個方法之後,在切換之前就呼叫beforeEach,切換之後,需要等待下載js完成,在onload裡面進行呼叫 afterEach
//切換之前一些處理
beforeEach:function(callback){
if(Object.prototype.toString.call(callback) === '[object Function]'){
this.beforeFun = callback;
}else{
console.trace('路由切換前鉤子函式不正確')
}
},
//切換成功之後
afterEach:function(callback){
if(Object.prototype.toString.call(callback) === '[object Function]'){
this.afterFun = callback;
}else{
console.trace('路由切換後回撥函式不正確')
}
},
通過以上的思路分析,再加以整合,我們就完成了一個簡單的前端路由,並且可以加到頁面進行實際的SPA開發,不過還是非常簡陋。
/*
*author:https://github.com/kliuj
**使用方法
* 1:註冊路由 : spaRouters.map('/name',function(transition){
//非同步載入js
spaRouters.asyncFun('name.js',transition)
//或者同步執行回撥
spaRouters.syncFun(function(transition){},transition)
})
2:初始化 spaRouters.init()
3:跳轉 href = '#/name'
*/
(function() {
var util = {
//獲取路由的路徑和詳細引數
getParamsUrl:function(){
var hashDeatail = location.hash.split("?"),
hashName = hashDeatail[0].split("#")[1],//路由地址
params = hashDeatail[1] ? hashDeatail[1].split("&") : [],//引數內容
query = {};
for(var i = 0;i<params.length ; i++){
var item = params[i].split("=");
query[item[0]] = item[1]
}
return {
path:hashName,
query:query
}
}
}
function spaRouters(){
this.routers = {};//儲存註冊的所有路由
this.beforeFun = null;//切換前
this.afterFun = null;
}
spaRouters.prototype={
init:function(){
var self = this;
//頁面載入匹配路由
window.addEventListener('load',function(){
self.urlChange()
})
//路由切換
window.addEventListener('hashchange',function(){
self.urlChange()
})
//非同步引入js通過回撥傳遞引數
window.SPA_RESOLVE_INIT = null;
},
refresh:function(currentHash){
var self = this;
if(self.beforeFun){
self.beforeFun({
to:{
path:currentHash.path,
query:currentHash.query
},
next:function(){
self.routers[currentHash.path].callback.call(self,currentHash)
}
})
}else{
self.routers[currentHash.path].callback.call(self,currentHash)
}
},
//路由處理
urlChange:function(){
var currentHash = util.getParamsUrl();
if(this.routers[currentHash.path]){
this.refresh(currentHash)
}else{
//不存在的地址重定向到首頁
location.hash = '/index'
}
},
//單層路由註冊
map:function(path,callback){
path = path.replace(/\s*/g,"");//過濾空格
if(callback && Object.prototype.toString.call(callback) === '[object Function]' ){
this.routers[path] ={
callback:callback,//回撥
fn:null //儲存非同步檔案狀態
}
}else{
console.trace('註冊'+path+'地址需要提供正確的的註冊回撥')
}
},
//切換之前一些處理
beforeEach:function(callback){
if(Object.prototype.toString.call(callback) === '[object Function]'){
this.beforeFun = callback;
}else{
console.trace('路由切換前鉤子函式不正確')
}
},
//切換成功之後
afterEach:function(callback){
if(Object.prototype.toString.call(callback) === '[object Function]'){
this.afterFun = callback;
}else{
console.trace('路由切換後回撥函式不正確')
}
},
//路由非同步懶載入js檔案
asyncFun:function(file,transition){
var self = this;
if(self.routers[transition.path].fn){
self.afterFun && self.afterFun(transition)
self.routers[transition.path].fn(transition)
}else{
console.log("開始非同步下載js檔案"+file)
var _body= document.getElementsByTagName('body')[0];
var scriptEle= document.createElement('script');
scriptEle.type= 'text/javascript';
scriptEle.src= file;
scriptEle.async = true;
SPA_RESOLVE_INIT = null;
scriptEle.onload= function(){
console.log('下載'+file+'完成')
self.afterFun && self.afterFun(transition)
self.routers[transition.path].fn = SPA_RESOLVE_INIT;
self.routers[transition.path].fn(transition)
}
_body.appendChild(scriptEle);
}
},
//同步操作
syncFun:function(callback,transition){
this.afterFun && this.afterFun(transition)
callback && callback(transition)
}
}
//註冊到window全域性
window.spaRouters = new spaRouters();
})()