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

2020-06-12 21:18:47易采站长站整理

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

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

修改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页面中的数据(猜想)。