浅谈浅谈Vue SPA 首屏加载优化实践首屏加载优化实践
写在前面写在前面
本文记录笔者在Vue SPA项目首屏加载优化过程中遇到的一些坑及优化方案!
我们以 vue-cli 工具为例,使用 vue-router 搭建SPA应用,UI框架选用 element-ui , ajax方案选用 axios, 并引入vuex ,使用
vuex-router-sync 将 router 同步到 store ,服务器使用本地Nginx服务。
构建项目构建项目
vue-init webpack vue-spa-starter-kit
cd vue-spa-starter-kit
npm install
npm install vuex element-ui axios -S
npm run dev
vue-cli会自动打开浏览器,可以看到效果。我们在入口文件中引入vue-router、element-ui、axios
// src/main.js
import 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import axios from 'axios'
import store from './store'
import router from './router'
import {sync} from 'vuex-router-sync'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.$http = axios
sync(store, router)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: { App }
})
接下来我们不做任何修改,使用默认的配置进行打包,Nginx采用默认配置,部署到Nginx,启动Nginx服务,查看效果:
可以看出,在没有开发任何页面及功能的情况下,vendor.js 有788kb。如果我们再依赖一些其他的库,比如 echarts
等,vendor.js 能到 1M 以上。
使用使用CDN资源资源
我们要将 vue、 vue-router、 vuex、element-ui 从 vendor.js 中分离出来,使用CDN资源引入。国内的CDN服务推荐使用
BootCDN。国外不是很好用。。。
首先在模板文件index.html中添加以下内容:
...
<head>
<link rel="stylesheet" href="https://cdn.bootcss.com/element-ui/2.0.7/theme-chalk/index.css" rel="external nofollow" >
</head>
<body>
<div id="app"></div>