1、骨架屏原理
骨架屏其实就是在数据加载到id为app的div之前,先放置一个显示,可以是代码亦可以是文字图片等,数据加载之后会覆盖显示
优势:首页加载慢会导致白屏、卡顿问题,骨架屏优化用户体验
2、结合webpack自定义插件,实现自定义骨架屏
步骤:
(1)在build目录新建一个js文件,作为自定义组件(代码在最后)
(2)在配置文件webpack.prod.config.js中注册引入
const MyPlugin = require('./MyPlugins')
(3)在配置文件webpack.prod.config.js中,插入自己的插件
骨架屏插件需要替换html,所以要放在html-webpack-plugin插件后面
new MyPlugin({
test:'xxx'
})
MyPlugin.js
// 使用webpack自己写的插件,来实现骨架屏的插入
let MyPlugin = function(options){
this.test = options.test
}
MyPlugin.prototype.apply = function(compiler){
// console.log('插件被执行了')
// console.log(this.test)
// console.log(compiler) // compiler.options获取webpack配置文件的属性
//先指定自己怎么编辑,根据别人的编译结果操作
compiler.plugin('compilation',compilation => {
// compilation对象可以操作一些东西
// webpack-plugin提供的接入点
compilation.plugin('html-webpack-plugin-before-html-processing',
(htmlData,callback) => {
// html-webpack-plugin 中间插入行为的地方
console.log(htmlData.html);
htmlData.html = htmlData.html.replace(
`<div id="app"></div>`,
`<div id="app">
<div id="user" style="background-color:hotpink;height:500px;display:none;">
user我是骨架屏A
</div>
<div id="goods" style="background-color:yellow;height:500px;display:none;">
goods我是骨架屏B
</div>
</div>
<script>
//不同组件实现不同骨架屏
// hash模式或者是history模式
let hashPath = location.hash; // #/user || #/goods
let hPath = location.pathname; // /user || /goods
if(hashPath === '#/user' || hPath === '/user'){
document.getElementById("user").style.display = 'block'
}else if(hashPath === '#/goods' || hPath === '/goods'){
document.getElementById("goods").style.display = 'block'
}
</script>
`
//更改了html,未来生成的html就是以上内容
);
//调用,不论如何两个参数,错误在前
callback(null,htmlData)
});
});
}
//向外导出插件
module.exports = MyPlugin;