vue+webpack骨架屏

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值