最近作項目發現一個問題,頁面每次刷新後加載速度都很是慢,20s左右,在開發環境則很是流暢,幾乎感受不到,本文參考望山的各類方案優化css
在config/index.js
文件中講productionSourceMap
設置爲false
,再次打包便沒有了map文件html
懶加載的實現方式有不少種,這裏簡單說三種實現方法vue
vue異步組件技術也就是異步加載,vue-router配置路由,使用veu的異步加載技術,能夠實現按需加載,可是這種狀況下一個組件生產一個js文件node
/* vue異步組件技術 */
{
path: '/index',
name: 'index',
component: resolve => require(['@/views/index'],resolve)
}
複製代碼
組件懶加載方案二webpack
// 下面2行代碼,沒有指定webpackChunkName,每一個組件打包成一個js文件。
const Home = () => import('@/components/home')
const Index = () => import('@/components/index')
// 下面2行代碼,指定了相同的webpackChunkName,會合並打包成一個js文件。 把組件按組分塊
const Home = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
const Index = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')
// router
{
path: '/about',
component: About
}, {
path: '/index',
component: Index
}
複製代碼
使用webpack的require.ensure()技術,也能夠實現按需加載.這種狀況下,多個路由指定相同的chunkName會合並打包成一個js文件ios
/* 組件懶加載方案三: webpack提供的require.ensure() */
{
path: '/home',
name: 'home',
component: r => require.ensure([], () => r(require('@/components/home')), 'demo')
}, {
path: '/index',
name: 'Index',
component: r => require.ensure([], () => r(require('@/components/index')), 'demo')
}
複製代碼
CDN能夠減小代碼體積加快請求速度,使用CDN主要解決兩個問題,打包時間太長,打包後代碼體積太大,請求很慢,還有就是迴避服務器帶寬問題web
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>vue-manage-system</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<script src="https://cdn.bootcss.com/vue/2.5.3/vue.js"></script>
<script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script>
<link rel="stylesheet" href="https://cdn.bootcss.com/element-ui/2.4.0/theme-chalk/index.css">
<script src="https://cdn.bootcss.com/element-ui/2.4.0/index.js"></script>
複製代碼
若是提示Element未定義,是由於Element依賴Vue,vue.js須要在element-ui以前引入,因此vue.js也要改成cnd的引入方式.vue-router
而後,修改/build/webpack.base.conf.js中修改配置。給module.exports添加externals屬性(詳見https://webpack.docschina.org/configuration/externals/),其中鍵是項目中引用的,值是所引用資源的名字。須要注意的是資源名須要查看所引用的JS源碼,查看其中的全局變量是什麼,例如element-ui的全局變量就說ELEMENTnpm
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter',
'ElementUI': 'ELEMENT',
'axios': 'axios',
}
}
複製代碼
而後刪除原先的import,若是不刪除原先的import,項目仍是會從node_modules中引入資源。 也就是說不刪的話,npm run build時候仍會將引用的資源一塊兒打包,生成文件會大很多。仍是刪了好。element-ui
參考文章列表:感謝大神們 vue頁面首次加載緩慢緣由及解決方案 vue項目實現按需加載的3種方式:vue異步組件、es提案的import()、webpack的require.ensure()