一:什么是单页面应用(SPA)
目前大家熟知的三大框架,vue,react,angular都属于SPA。 是一种网页应用或网站的设计模式,它在浏览器中仅加载一个html页面,并动态的更新改页面,而不是每一个新页面加载新的html。
二:SPA和MPA的区别
MPA:多页面应用。每个页面都是一个主页面,都是独立的,当我们访问另一个页面的时候,需要重新加载html,js,css文件,公共文件则根据需求按需加载。
| 要点 | 单页面应用(SPA) | 多页面应用 |
|---|---|---|
| 组成 | 一个主页面和多个页面片段 | 多个主页面 |
| 刷新方式 | 局部刷新 | 整页刷新 |
| url模式 | 哈希模式 | 历史刷新 |
| SEO搜索引擎优化 | 难实现,但是可以用SSR改善 | 容易实现 |
| 数据传递 | 容易 | 通过url,cookie,localStorge等传递 |
| 页面切换 | 速度快,用户体验良好 | 切换加载资源,速度慢,用户体验差 |
| 维护成本 | 相对容易 | 相对复杂 |
三:单页面应用优缺点
优点:
- 具有桌面应用的即时性,网站的可移植性和可访问性
- 用户体验好,快,内容改变不需要加载整个页面
- 良好的前后端分离,分工更明确
缺点:
- 不利于搜索引擎的抓取
- 首次渲染速度相对比较慢
四:如何实现一个SPA
原理: 1,监听地址栏中hash变化驱动界面变化 2,用pushstate记录浏览器的历史,驱动界面发送变化 实现: hash模式 核心通过监听url中的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('/')
miniRouter.push('/page2')
history模式 history模式核心借用HTML5 history api,api提供了丰富的router相关属性
先了解一下几个相关api:
history.pushState 浏览器历史记录添加记录
history.replaceState 修改浏览器历史记录中当前记录
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')
五:如何给SPA做SEO
需要进一步弄懂,先占位
实现seo的三种方式
1,SSR服务端渲染
2,静态化
3,使用Phantomjs针对爬虫处理