·vincent
SPA单页面应用的理解
单页面的理解
SPA
SPA单页面的概念
SPA( single-page application )仅在 Web 页面初始化时加载相应的 HTML、JavaScript 和 CSS。一旦页面加载完成,SPA 不会因为用户的操作而进行页面的重新加载或跳转;取而代之的是利用路由机制实现 HTML 内容的变换,UI 与用户的交互,避免页面的重新加载。
优点
- 用户体验好、快,内容的改变不需要重新加载整个页面,避免了不必要的跳转和重复渲染;
- 基于上面一点,SPA 相对对服务器压力小;
- 前后端职责分离,架构清晰,前端进行交互逻辑,后端负责数据处理
缺点
- 初次加载耗时多:为实现单页 Web 应用功能及显示效果,需要在加载页面的时候将 JavaScript、CSS 统一加载,部分页面按需加载;
- 前进后退路由管理:由于单页应用在一个页面中显示所有的内容,所以不能使用浏览器的前进后退功能,所有的页面切换需要自己建立堆栈管理;
- SEO 难度较大:由于所有的内容都在一个页面中动态替换显示,所以在 SEO 上其有着天然的弱势
单页应用与多页应用的区别
单页面应用(SPA) | 多页面应用(MPA) | |
---|---|---|
组成 | 一个主页面和多个页面片段 | 多个主页面 |
刷新方式 | 局部刷新 | 整页刷新 |
url模式 | Hash模式 | History 模式 |
SEO搜索引擎优化 | 难实现,可以使用SSR方式改善 | 容易实现 |
数据传递 | 容易 | 通过url, cookie, localStorage等传递 |
页面切换 | 速度快,体验好 | 切换加载资源速度慢 用户体验差 |
维护成本 | 相对容易 | 相对复杂 |
实现一个SPA
-
监听地址栏中 hash 变化驱动界面变化
-
用pushstate 记录浏览器的历史,驱动界面发生变化
hash 模式
核心通过监听url中的hash来进行路由跳转
js
1// 定义 Router
2class Router {
3 constructor () {
4 this.routes = {}; // 存放路由path及callback
5 this.currentUrl = '';
6
7 // 监听路由change调用相对应的路由回调
8 window.addEventListener('load', this.refresh, false);
9 window.addEventListener('hashchange', this.refresh, false);
10 }
11
12 route(path, callback){
13 this.routes[path] = callback;
14 }
15
16 push(path) {
17 this.routes[path] && this.routes[path]()
18 }
19}
20
21// 使用 router
22window.miniRouter = new Router();
23miniRouter.route('/', () => console.log('page1'))
24miniRouter.route('/page2', () => console.log('page2'))
25
26miniRouter.push('/') // page1
27miniRouter.push('/page2') // page2
history模式
history 模式核心借用 HTML5 history api,api 提供了丰富的 router 相关属性先了解一个几个相关的api
- history.pushState 浏览器历史纪录添加记录
- history.replaceState修改浏览器历史纪录中当前纪录
- history.popState 当 history 发生变化时触发
js
1// 定义 Router
2class Router {
3 constructor () {
4 this.routes = {};
5 this.listerPopState()
6 }
7
8 init(path) {
9 history.replaceState({path: path}, null, path);
10 this.routes[path] && this.routes[path]();
11 }
12
13 route(path, callback){
14 this.routes[path] = callback;
15 }
16
17 push(path) {
18 history.pushState({path: path}, null, path);
19 this.routes[path] && this.routes[path]();
20 }
21
22 listerPopState () {
23 window.addEventListener('popstate' , e => {
24 const path = e.state && e.state.path;
25 this.routers[path] && this.routers[path]()
26 })
27 }
28}
29
30// 使用 Router
31
32window.miniRouter = new Router();
33miniRouter.route('/', ()=> console.log('page1'))
34miniRouter.route('/page2', ()=> console.log('page2'))
35
36// 跳转
37miniRouter.push('/page2') // page2