背景: 中台管理系统,在生产环境上偶尔会出现用户首次访问登录页,页面加载时间超过长,甚至加载不出来的情况。
优化一:gzip静态文件打包压缩。
在nginx.conf文件内,对gzip进行配置
gzip_static on;
在webpack中添加插件
new CompressionPlugin({
test: /.js$|.html$|.css/, // 匹配文件名
threshold: 10240, // 对超过10kb的数据进行压缩
deleteOriginalAssets: false // 是否删除原文件
})
优化二:限制单个静态资源文件大小
在webpack配置中添加插件,build生成的bundle包进行代码分割,实现单个文件大小变得更小。
config.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\/]node_modules[\/]/,
priority: 10,
chunks: 'initial', // only package third parties that are initially dependent
maxSize: 200000,
minSize: 100000
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\/]node_modules[\/]_?element-ui(.*)/, // in order to adapt to cnpm
maxSize: 300000,
minSize: 100000
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
效果测试
在浏览器上开启停用缓存的模式下,模拟首次加载场景
优化之前下载的资源文件大小合计:传输文件3.7M
完成时间平均值为如下
正常模式- 2.3s
低速3G- 100s
优化之后下载的资源文件大小合计:传输文件1.7M (解压后3.6M)
时间平均值为如下
正常模式- 2s
低速3G- 45s
结论:
在正常或者高速的带宽网速的情况下,提升效果不明显(2.3s -> 2s)
在弱网或者网络波动的情况下,页面首次加载的时间大幅缩短,节省了一半的加载耗时。 (100s -> 45s)
同时在传输文件的大小合计上,从原来的3.7M 减少 到 1.7M