vue打包文件后首次加载速度慢解决方法----1.压缩文件js.css 2.使用cdn加载

问题描述:
300kb的文件加载速度用了5s
 
 
1.首先肯定要去掉.map文件
在 config/index.js 文件中将productionSourceMap 的值设置为false. 再次打包就可以看到项目文件中已经没有map文件
 
productionSourceMap: false,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
2.vue-router路由懒加载
 
3.使用gzip压缩
 
1),在安装完依赖插件后,修改config/index.js 文件下 productionGzip:true ;
开启productionGzip功能必须先install --save-dev compression-webpack-plugin @1.1.12 使用低版本否则会报错
// 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,
productionGzipExtensions: ['js', 'css'],
2),然后在 webback.prod.config.js 中添加如下代码
 
 3),最后在Nginx 下开启gzip 。
首先安装Nginx 服务器,然后将项目文件部署到html文件目录下,如果端口被占用,可以修改 config/nginx.conf 文件中listen:somename 来修改端口。
开启gzip:
在config/nginx.config 添加如下配置。
 
http:{
      gzip on;
      gzip_static on;
      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;
}
 
修改完成后,reload一下,重启服务。
4,使用CDN加载    原文链接: https://blog. csdn.net/LonewoIf/article/details/87777367
在打包后发现vendor.js 文件占用内存特别大,这里面主要是使用的一些第三方库,例如 vuex,vue-router,axios,elementUI 等文件
我们除了在使用过程中单个组件引用,还可以使用CDN 加载。
通过在index.html 中直接引入第三方资源来缓解我们服务器的压力,其原理是将我们的压力分给了其他服务器站点。
1)引入资源。 在 index.html 中,添加CDN资源,
<!-- 引入Vue.js -->
<script src="https://cdn.staticfile.org/vue/2.4.3/vue.min.js"></script>
<!-- 引入vuex.js -->
<script src="https://cdn.staticfile.org/vuex/3.0.0/vuex.min.js"></script>
<!-- 引入vue-router -->
<script src="https://cdn.staticfile.org/vue-router/3.0.0/vue-router.min.js"></script>
<!-- 引入组件库 -->
<script src="https://cdn.staticfile.org/element-ui/2.4.3/index.js"></script>
<!-- 引入样式 -->
<link href="https://cdn.staticfile.org/element-ui/2.4.3/theme-chalk/index.css" rel="stylesheet">
<!-- 引入echarts -->
<script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
 
 
2)添加配置   在 bulid/webpack.base.conf.js 文件中,增加 externals,将引用的外部模块导入,
第三步:去掉原有的引用
去掉 import:
// import Vue from "vue";
// 引入element 组件
// import ElementUI from "element-ui";
// import "element-ui/lib/theme-chalk/index.css";
// import VueRouter from "vue-router";
// import Vuex from "vuex";
去掉 Vue.use(xxx):
// Vue.use(ElementUI);
// Vue.use(VueRouter);
// Vue.use(Vuex);
重新 npm run build,会看到此时 vendor.js 体积有所减小了很多。通过开发者模式的Network工具,可以看到 vue.js、vuex.js、vendor.js 等文件会分别由一个线程进行加载。且因为使用了CDN,减轻了带宽压力。
 
注意事项:
    1、在第一步引入资源时注意 vue.js 必须在 vue-router、vuex、element-ui 之前引入。
    2、在第二步修改配置时注意 “element-ui”: “ELEMENT” 是固定写法不能更改。
    3、如果 element-ui 采用 cdn 引入的方式,vue 不采用 cdn 引入的方式,
这样打包以后打开 dist 下的 index.html 时页面空白报错,必须 vue 和 element-ui 都采用 cdn 引入的方式。 
 

猜你喜欢

转载自www.cnblogs.com/jiayeyuan/p/12609694.html
今日推荐