js实现路由按需加载以及单页面原理

正文开始

<pre>var wapRouter = { loadedOnes: {}, checkHasLoad: function (routerName) { return isUndefined(wapRouter.loadedOnes[routerName]) ? false : true; }, _hashChangeFromUs : false, //初始化所有接口 'init': function () { var path_ = ''; $.each(wapRouter.routers, function (router_, obj_) { Object.defineProperty(wapRouter, router_, { get: function () { if(wapRouter.checkHasLoad(router_)) { wapRouter._hashChangeFromUs = true; window.location.hash = router_; wapRouter.loadedOnes[router_](); //释放当前调转 下次onhashchange继续可以侦听 setTimeout(function () { wapRouter._hashChangeFromUs = false; }, 200); } else { wapRouter._hashChangeFromUs = true; window.location.hash = router_; //path 不能取obj_的path 因为每次获取的时候 each已经过期 path_ = wapRouter.routers[router_]['path']; // console.log('router_:'+ router_); // console.log('path_:'+ path_); $.ajax({ url: path_, success: function (string) { var newObj = eval(string); wapRouter.loadedOnes[router_] = newObj; newObj(); wapRouter._hashChangeFromUs = false; }, error: function () { console.log('path加载失败:'+ path_); } }); return {}; } } }); }); //获取页面hash var _gethash = function(){ return window.location.hash.replace(/^#/,""); }; //检测url的hash 自动跳转 var _checkUrlHash = function() { var router_ = _gethash(); if(!router_) { return; } console.log(router_); wapRouter[router_]; //运行页面 }; //页面后退 跟踪url window.onhashchange = function() { if(wapRouter._hashChangeFromUs == true) return; // console.log('wapRouter._hashChangeFromUs'); // console.log(wapRouter._hashChangeFromUs); _checkUrlHash(); }; }, //wap页面所有路由 routers: { // 'example_login': { // 'path': '/assets/wap/js/login.js' // } //js内容 // (function() { // console.log('我要登录'); // }); }, }; //定义所有路由 wapRouter.routers = { 'login': { 'path': '/assets/wap/js/login.js' }, 'reg': { 'path': '/assets/wap/js/reg.js' } }; wapRouter.init();</pre>

正文结束

js 正则替换返回值做回调函数 blob转base64位 base64位转blob