vue项目前端性能优化总结

670 阅读1分钟

0. 路由懒加载

路由组件不使用直接引入,而是匿名函数返回形式,如下注释可以定义编译后的js文件名,在未进入该路由时此js文件的内容将不会被请求到:

{
    path: '/home',
    component: () => import(/* webpackChunkName: 'base' */ '@/views/Index.vue')
}

1. 开启gzip压缩

1.1. 需要服务端做配置开启gzip功能,例如我的是nginx.conf配置:

    gzip on;
    gzip_min_length 80k;
    gzip_buffers 4 16k;
    gzip_comp_level 5;
    gzip_types text/plain application/javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

1.2. vue.config.js配置编译gzip,npm安装相关插件:

const CompressionWebpackPlugin = require('compression-webpack-plugin')
module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8
        })
      );
    }
  },
}

2. 使用插件压缩混淆去注释

const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      config.plugins.push(
        new TerserPlugin({
          cache: true,
          parallel: true,
          sourceMap: false,
          terserOptions: {
            compress: {
              drop_console: true,
              drop_debugger: true
            }
          }
        })
      );
    }
  },
}

3. 去掉多余的第三方库

3.1. 删除库npm指令:npm uninstall xxx

3.2. 把非必要库放到服务端,如处理时间常用库moment.js,引入比较大,建议放在后端,或者使用代替方案如day.js,有时间精力也可以自行封装方法,但是重复造车轮不推荐。

3.3. (可选)提取第三方库,不使用import方式引入,而是使用其cdn链接直接在public中的index.html中使用传统方式引入,有利于减少编译包体积。

4. 资源CDN

资源文件CDN,像图片资源我都是放在七牛云储存,从不放服务器,七牛云好像配置域名就可以cdn加速了,比较方便。如果客户端有特殊自定义需要,如全国地址要自行配置,其配置文件也比较大,也要提取出来,不要放客户端中打包。

configureWebpack: config => {
    if (isProduction) {
      config.plugins.push(
      .....
      // 分离包
      config.externals = {
        'vue': 'Vue',
        'vue-router': 'VueRouter',
        'vuex': 'Vuex',
        'axios': 'axios'
      }
    }
  },

5. 图片预加载

防止多图或图片较大时对客户端浏览体验产生影响:

export default class PreLoad {
    private i: number;
    private arr: string[];
    constructor(arr: string[]) {
        this.i = 0
        this.arr = arr
    }
    public imgs() {
        return new Promise(resolve => {
            const work = (src: string) => {
                if (this.i < this.arr.length) {
                    const img = new Image()
                    img.src = src;
                    if (img.complete) {
                        work(this.arr[this.i++])
                    } else {
                        img.onload = () => {
                            work(this.arr[this.i++])
                            img.onload = null;
                        };
                    }
                    // console.log(((this.i + 1) / this.arr.length) * 100);
                } else {
                    resolve()
                }
            }
            work(this.arr[this.i])
        })
    }
}

加个转圈菊花或者加载动画/提示等,然后调用该方法来阻塞页面:

const imgs = ['http://XX.png','http://XX.png']
const preload = new this.$utils.preload(imgs)
const preDone = await preload.imgs()

题外

1. 常见前端优化的三个层面:网络请求,JS优化,CSS优化

  • 减少http请求
  • 图片懒加载
  • 使用字体图标或svg,尽量不使用png,png尽量使用css图片精灵
  • 避免使用闭包,减少DOM回流重绘,避免使用css表达式
  • 不使用cookie,不使用iframe,不使用flash
  • 尽量减少引用大量第三方库 (减少资源大小)

2. 在新版的vue-cli工具中GUI界面有集成了不错的分析工具,可以直观的看到项目的编译文件大小情况,对此针对性的分析改进代码也是重要的优化手段。

image.png image.png