天天看點

vue白屏或加載慢_Vue首屏加載慢的優化方案

使用vue建構項目首屏加載時,出現加載慢,白屏的問題解決方案:

步驟一 webpack來打包vue項目,vendor.js過大問題解決

1.造成過大的原因是因為在main.js導入第三庫太多時,webpack合并js時生成了vendor.js(我們習慣把第三方庫放在vendor裡面)造成的.如下圖在main.js引用了一些第三方庫。導緻了你的伺服器端的js檔案越大則使用者加載頁面的時間會越長(因為所需下載下傳js的時間越久)

首先在index.html中,使用CDN的資源,複制以下bootstrap的連結資源:

2.在bulid/webpack.base.conf.js檔案中,添加externals,導入index.html下所需的資源子產品:

module.exports = {

context: path.resolve(__dirname, '../'),

entry: {

app: ['babel-polyfill', 'lib-flexible', './src/main.js']

},

externals: { //

vue: 'Vue',

vuex: 'Vuex',

'vue-router': 'VueRouter',

VueAwesomeSwiper: 'VueAwesomeSwiper'

},

3.在main.js裡将以下 import 注釋 替換 require 引入子產品

// import Vue from 'vue'

// import VueAwesomeSwiper from 'vue-awesome-swiper'

const Vue = require('vue')

const VueAwesomeSwiper = require('VueAwesomeSwiper')

Vue.use(VueAwesomeSwiper)

4.當然可以在生産環境當中删除掉不必要的console.log

打開build/webpack.prod.conf.js 在plugins裡添加以下代碼

plugins: [

new webpack.optimize.UglifyJsPlugin({ //添加-删除console.log

compress: {

warnings: false,

drop_debugger: true,

drop_console: true

},

sourceMap: true

}),

5.執行npm run build

在控制台當中可以看到檔案壓縮的記錄

static/js/vendor.50304a716a06fb947df7.js 的size

我這裡一開始有450k 當優化完以後整整小了一半多 222kB(當你用了一些ui元件庫替換成cdn說不定更大的驚喜)

vue白屏或加載慢_Vue首屏加載慢的優化方案

sizexiao.png

6.最後可以通過打開項目測試在首屏加載時有着明顯的打開提速效果!

步驟二 vue-cli開啟打包壓縮 和背景配合 gzip通路

1.首先打開 config/index.js ,找到 build 對象中的 productionGzip ,改成 true

打開 productionGzip: true 之前,先要安裝依賴 compression-webpack-plugin ,官方推薦的指令是:

npm install --save-dev compression-webpack-plugin

//(此處有坑) 如果打包報錯,應該是版本問題 ,先解除安裝之前安裝的此插件 ,然後安裝低版本

npm install --save-dev [email protected]

3.等安裝好了,重新打包 npm run build ,此時打包的檔案會 新增 .gz 檔案。是不是比原來的js檔案小很多呢,之後項目通路的檔案就是這個.gz檔案

4.背景nginx開啟gzip模式通路,浏覽器通路項目,自動會找到 .gz 的檔案。加載速度明顯提高。

開啟 nginx gzip ,在 nginx.conf 配置檔案中 配置

http { //在 http中配置如下代碼,

gzip on;

gzip_disable "msie6";

gzip_vary on;

gzip_proxied any;

gzip_comp_level 8; #壓縮級别

gzip_buffers 16 8k;

#gzip_http_version 1.1;

gzip_min_length 100; #不壓縮臨界值

gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

}

儲存退出 ,并 重新開機 nginx

systemctl reload nginx.service

systemctl restart nginx.service

5 測試通路

curl -I -H "Accept-Encoding: gzip, deflate" "http://xxx.com" //通路請求中 Content-Encoding: gzip 表示 壓縮成功頁面,

同理 通路js,css等 可測試 是否壓縮成功.

6 最後通路項目,進入首頁的時候加載速度會有所提升