VUE单页应用首屏加载速度优化方案

单页应用会随着项目越大,导致首屏加载速度很慢!!!以下给出在下知道的几种优化方案

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

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

  • 在index.html中引入cdn资源
...
  <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
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
// import Vue from 'vue'
// import VueResource from 'vue-resource'
// Vue.use(VueResource)

路由懒加载

require.ensure方式

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')

import方式

const workCircle = () => import('@/module/work-circle/Index')

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

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

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

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

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

《VUE单页应用首屏加载速度优化方案》

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

webpack开启gzip压缩。 只需要服务器开启gzip压缩,服务器开启gzip压缩后,服务器拿到我们部署上去的文件,会压缩文件然后返回给浏览器。所以前端使用gzip压缩是没有起作用的。所以compression-webpack-plugin插件有什么用,各位探讨下QAQ

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

《VUE单页应用首屏加载速度优化方案》

webpack4.x以下使用compression-webpack-plugin插件,插件版本应使用1.x

webpack4.x版本以上可以使用compression-webpack-plugin 2.x

  • config/index.js中
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构建项目时,默认会有这段代码

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
    })
  )
}

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

使用uglifyjs-webpack-plugin插件代替webpack自带UglifyJsPlugin插件

两个插件都不支持es6压缩,所以使用此插件前需要用工具(如babel-loader)转换es6代码

问题描述:项目中使用iview时,导致使用UglifyJsPlugin压缩报错

因为iview某插件中包含es6语法。然而两个插件都不支持es6压缩

解决方法如下:

  • 修改webpack配置文件,使用babel-loader转换一下iview插件中的es6语法
module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
...
  module: {
    loaders: [
      { test: /iview.src.*?js$/, loader: 'babel' },
      { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }
    ],
    rules: [
    ...
      {
        test: /\.js$/,
        loader: 'babel-loader',
         // resolve('/node_modules/iview/src'),resolve('/node_modules/iview/packages')解决iview打包时UglifyJs报错
        include: [resolve('src'), resolve('test'), resolve('/node_modules/iview/src'),resolve('/node_modules/iview/packages')]
      }
      ...
    ]
  }
}
  • webpack生产环境中
...
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
...
    new UglifyJsPlugin({
      // 使用外部引入的新版本的js压缩工具
      parallel: true,
      uglifyOptions: {
        ie8: false, // 启用IE8支持
        ecma: 6, // 支持的ECMAScript的版本(5,6,7或8)。影响parse,compress&& output选项
        warnings: false, // 显示警告
        mangle: true, // debug false
        output: {
          comments: false,
          beautify: false, // debug true
        },
        compress: {
          // 在UglifyJs删除没有用到的代码时不输出警告
          warnings: false,
          // 删除所有的 `console` 语句
          // 还可以兼容ie浏览器
          drop_console: true,
          // 内嵌定义了但是只用到一次的变量
          collapse_vars: true,
          // 提取出出现多次但是没有定义成变量去引用的静态值
          reduce_vars: true,
        }
      }
    }),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: false
    //   },
    //   sourceMap: true
    // }),

此方法有待实践,留待下次分享 ==

    原文作者:停停儿
    原文地址: https://segmentfault.com/a/1190000016155447
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞