# 四.性能优化(骨架屏)
前言
vue 项目中需要优化的地方,以及相关的解决方案
# 1.预渲染
npm i prerender-spa-plugin
1
缺陷数据不够动态,可以使用 ssr 服务端渲染
const PrerenderSPAPlugin = require("prerender-spa-plugin")
const path = require("path")
module.exports = {
configureWebpack: {
plugins: [
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, "dist"),
routes: ["/", "/about"],
}),
],
},
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 2.骨架屏
配置 webpack 插件 vue-skeleton-webpack-plugin
单页骨架屏幕
import Vue from "vue"
import Skeleton from "./Skeleton.vue"
export default new Vue({
components: {
Skeleton: Skeleton,
},
template: `
<Skeleton></Skeleton>
`,
})
// 骨架屏
plugins: [
new SkeletonWebpackPlugin({
webpackConfig: {
entry: {
app: resolve("./src/entry-skeleton.js"),
},
},
}),
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
带路由的骨架屏,编写 skeleton.js 文件
import Vue from "vue"
import Skeleton1 from "./Skeleton1"
import Skeleton2 from "./Skeleton2"
export default new Vue({
components: {
Skeleton1,
Skeleton2,
},
template: `
<div>
<skeleton1 id="skeleton1" style="display:none"/>
<skeleton2 id="skeleton2" style="display:none"/>
</div>
`,
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new SkeletonWebpackPlugin({
webpackConfig: {
entry: {
app: path.join(__dirname, "./src/skeleton.js"),
},
},
router: {
mode: "history",
routes: [
{
path: "/",
skeletonId: "skeleton1",
},
{
path: "/about",
skeletonId: "skeleton2",
},
],
},
minimize: true,
quiet: true,
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
优化白屏效果 实现骨架屏插件
class MyPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.plugin(
"html-webpack-plugin-before-html-processing",
(data) => {
data.html = data.html.replace(
`<div id="app"></div>`,
`
<div id="app">
<div id="home" style="display:none">首页 骨架屏</div>
<div id="about" style="display:none">about页面骨架屏</div>
</div>
<script>
if(window.hash == '#/about' || location.pathname=='/about'){
document.getElementById('about').style.display="block"
}else{
document.getElementById('home').style.display="block"
}
</script>
`
)
return data
}
)
})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28