1.是什么?
SPA(单页面应用)就是一个HTML文件可以完成多个页面的切换功能实现。
MPA(多页面应用)指的是整体页面内容全部会被更新替换,即使有共同的内容都会被全部替换成b页面的页面结构。
2.优缺点?
优点:
1.具有桌面应用的即时性、网站的可移植性和可访问性
2.用户体验好、快,内容的改变不需要重新加载整个页面
3.良好的前后端分离,分工更明确
缺点:
- 不利于搜索引擎的抓取
- 首次渲染速度相对较慢
3.如何实现一个SPA
原理:
监听地址栏中hash变化驱动界面变化
用pushsate记录浏览器的历史,驱动界面发送变化
实现
hash 模式`
在这里插入代码片
// 定义 Router
class Router {
constructor () {
this.routes = {}; // 存放路由path及callback
this.currentUrl = '';
// 监听路由change调用相对应的路由回调
window.addEventListener('load', this.refresh, false);
window.addEventListener('hashchange', this.refresh, false);
}
route(path, callback){
this.routes[path] = callback;
}
push(path) {
this.routes[path] && this.routes[path]()
}
}
// 使用 router
window.miniRouter = new Router();
miniRouter.route('/', () => console.log('page1'))
miniRouter.route('/page2', () => console.log('page2'))
miniRouter.push('/') // page1
miniRouter.push('/page2') // page2
history模式
history 模式核心借用 HTML5 history api,api 提供了丰富的 router 相关属性先了解一个几个相关的api
1.history.pushState 浏览器历史纪录添加记录
2. history.replaceState修改浏览器历史纪录中当前纪录
3.history.popState 当 history 发生变化时触发
// 定义 Router
class Router {
constructor () {
this.routes = {};
this.listerPopState()
}
init(path) {
history.replaceState({path: path}, null, path);
this.routes[path] && this.routes[path]();
}
route(path, callback){
this.routes[path] = callback;
}
push(path) {
history.pushState({path: path}, null, path);
this.routes[path] && this.routes[path]();
}
listerPopState () {
window.addEventListener('popstate' , e => {
const path = e.state && e.state.path;
this.routers[path] && this.routers[path]()
})
}
}
// 使用 Router
window.miniRouter = new Router();
miniRouter.route('/', ()=> console.log('page1'))
miniRouter.route('/page2', ()=> console.log('page2'))
// 跳转
miniRouter.push('/page2') // page2