基于Vue的单页应用,首屏加载优化方案

我实际的项目首屏加载从 12s 左右优化到 4s 左右。由于是演示项目,并没有开发其他的页面和功能,效果不是很明显,大家可以自行踩坑。大家有更好的方案,可以共同学习!

我们以 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-routerelement-uiaxios

// 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、 vuexelement-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">
    </head>
    <body>
      <div id="app"></div>
      <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
      <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
      <script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>
      <script src="https://cdn.bootcss.com/element-ui/2.0.7/index.js"></script>
      <!-- built files will be auto injected -->
    </body>
    
  • 修改 build/webpack.base.conf.js。关于 externals 配置项请自行查阅相关资料。

    module.exports = {
      ...
      externals: {
        'vue': 'Vue',
        'vuex': 'Vuex',
        'vue-router': 'VueRouter',
        'element-ui': 'ElementUI'
      }
      ...
    }
    
  • 修改 src/router/index.js

    // import Vue from 'vue'
    import VueRouter from 'vue-router'
    // 注释掉
    // Vue.use(VueRouter)
    ...
    
  • 修改 src/store/index.js

    ...
    // 注释掉
    // Vue.use(Vuex)
    ...
    
  • 修改 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 ELEMENT from 'element-ui'
    // import 'element-ui/lib/theme-chalk/index.css'
    
    Vue.config.productionTip = false
    
    Vue.use(ELEMENT)
    Vue.prototype.$http = axios
    
    sync(store, router)
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      store,
      router,
      template: '<App/>',
      components: { App }
    })
    

    注意!这里 element-ui 变量名要使用 ELEMENT,因为element-ui的 umd 模块名是 ELEMENT

再次打包,部署到Nginx服务,可以看到:

 

vendor.js 减少到了 112kb,提升85.5%!

再看CDN资源:

 

可以看出,5个请求共216kb,耗时619ms!

Nginx 开启 gzip

对 vendor.js 我们优化完了,接下来我们优化服务器上的资源。先看看没有开启 gzip 的效果:

 

可以看到有 13.5kb

Nginx开启gzip,修改nginx配置文件 nginx.conf:

...

http {
    ...
    
    gzip               on;
    gzip_min_length    1k;
    gzip_buffers       4  16k;
    #gzip_http_version  1.1;
    gzip_comp_level    2; # 压缩级别
    # 要压缩的mine类型
    gzip_types         text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss image/jpeg image/gif image/png image/svg+xml;
    gzip_vary          off;
    gzip_proxied       expired no-cache no-store private auth;
    gzip_disable       "MSIE [1-6]\."; # IE6不支持gzip
    
    ...
}

关于 nginx gzip,请自行查阅相关资料

重启nginx服务,再看效果:

 

可以看到服务器上的资源经过gzip压缩之后有 9kb,压缩比 13.3%。

总结

  • 使用CDN资源,减小服务器带宽压力
  • 路由懒加载
  • 将一些静态js css放到其他地方(如OSS),减小服务器压力
  • 按需加载三方资源,如iview,建议按需引入iview中的组件
  • 使用nginx开启gzip减小网络传输的流量大小
  • webpack开启gzip压缩
  • 若首屏为登录页,可以做成多入口,登录页单独分离为一个入口

使用CDN资源,减小服务器带宽压力

在index.html中引入cdn资源

?

1

2

3

4

5

6

7

8

9

10

11

...

 <body>

  <div id="app">

  </div>

  <!-- built files will be auto injected -->

  <script src="https://cdn.bootcss.com/vue/2.5.2/vue.min.js"></script>

  <script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>

  <script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>

  <script src="https://cdn.bootcss.com/vue-resource/1.5.1/vue-resource.min.js"></script>

 </body>

 ...

修改 build/webpack.base.conf.js

?

1

2

3

4

5

6

7

8

9

10

11

12

13

module.exports = {

 context: path.resolve(__dirname, '../'),

 entry: {

  app: './src/main.js'

 },

 externals:{

  'vue': 'Vue',

  'vue-router': 'VueRouter',

  'vuex':'Vuex',

  'vue-resource': 'VueResource'

 },

 ...

}

修改src/main.js src/router/index.js 注释掉import引入的vue,vue-resource

?

1

2

3

// import Vue from 'vue'

// import VueResource from 'vue-resource'

// Vue.use(VueResource)

路由懒加载

?

1

2

const workCircle = r => require.ensure([], () => r(require('@/module/work-circle/Index')), 'workCircle')

const workCircleList = r => require.ensure([], () => r(require('@/module/work-circle/page/List')), 'workCircleList')

将一些静态js css放到其他地方(如OSS),减小服务器压力

注意这里的js文件,需要将结果抛出,然后在需要用到该js的组件中import引入

按需加载三方资源,如iview,建议按需引入iview中的组件

按需引用请查看iview官方文档iview

使用nginx开启gzip减小网络传输的流量大小

配置nginx,可以参考Nginx开启Gzip压缩大幅提高页面加载速度

webpack开启gzip压缩

这里需要配合Nginx服务器,Nginx开启gzip

config/index.js中

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

module.exports = {

 build: {

  ...

  // Gzip off by default as many popular static hosts such as

  // Surge or Netlify already gzip all static assets for you.

  // Before setting to `true`, make sure to:

  // npm install --save-dev compression-webpack-plugin

  productionGzip: true, // 就是这里开启gzip,vue-cli搭建项目,这里默认为false

  productionGzipExtensions: ['js', 'css'],

 

  // Run the build command with an extra argument to

  // View the bundle analyzer report after build finishes:

  // `npm run build --report`

  // Set to `true` or `false` to always turn it on or off

  bundleAnalyzerReport: process.env.npm_config_report

 }

}

build/webpack.prod.conf.js中

使用vue-cli构建项目时,默认会有这段代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

if (config.build.productionGzip) {

 const CompressionWebpackPlugin = require('compression-webpack-plugin')

 webpackConfig.plugins.push(

  new CompressionWebpackPlugin({

   asset: '[path].gz[query]',

   algorithm: 'gzip',

   test: new RegExp(

    '\\.(' +

    config.build.productionGzipExtensions.join('|') +

    ')$'

   ),

   threshold: 10240,

   minRatio: 0.8

  })

 )

}

若首屏为登录页,可以做成多入口,登录页单独分离为一个入口

修改webpack配置

在原先只有一个入口叫app的基础上,再加一个叫login的入口,指向另一个入口js文件;

既然是两个页面,那么原先只有一个的HtmlWebpackPlugin也需要再添加一个,并且filename和template改成登录页的;

HtmlWebpackPlugin默认会把所有资源放进html,为了去掉不需要的资源,需要在HtmlWebpackPlugin选项里分别添加excludeChunks: ['login']和excludeChunks: ['app'];

原先的某些CommonsChunkPlugin会导致报错,删掉只剩下一个manifest的CommonsChunkPlugin就好。

添加登录相关文件

添加之前配好的login入口文件,与app类似,但是去掉登录页不需要的东西,如用不到的组件和样式等;

添加login入口专用的router配置文件,去掉其他路由,只留下登录页一个就好:

只留登录路由

添加登录页的html模板,也是去掉登录里用不到的资源。

修改其他细节

登录完不是用vue-router的push方法,而是改成直接修改location.href跳到另一个页面;

去除原来app路由中的login;

登录页中可以使用隐藏的iframe等方式预加载app页面中的数据(猜想)。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值