时间:2021-07-01 10:21:17 帮助过:59人阅读
单页应用会随着项目越大,导致首屏加载速度很慢!!!以下给出在下知道的几种优化方案
使用CDN资源,减小服务器带宽压力
路由懒加载
将一些静态js css放到其他地方(如OSS),减小服务器压力
按需加载三方资源,如iview,建议按需引入iview中的组件
使用nginx开启gzip减小网络传输的流量大小
webpack开启gzip压缩
若首屏为登录页,可以做成多入口,登录页单独分离为一个入口
在index.html中引入cdn资源
- ...
- <body>
- <p id="app">
- </p>
- <!-- 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)
- 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文件,需要将结果抛出,然后在需要用到该js的组件中import引入
按需引用请查看iview官方文档iview
配置nginx,可以参考Nginx开启Gzip压缩大幅提高页面加载速度
这里需要配合Nginx服务器,Nginx开启gzip
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
- })
- )
- }
若首屏为登录页,可以做成多入口,登录页单独分离为一个入口
相关推荐:
Vue怎么使用CDN优化首屏加载的速度
js延迟加载思想和首屏延迟加载讲解
以上就是vue中如何优化单页应用首屏加载速度(详细)的详细内容,更多请关注Gxl网其它相关文章!