vue2 、 vue3首屏优化,减少白屏时间

在第一帧的时候加载应该被用户看到的页面部分,剩下的逐步加载

1. 使用v-for来模拟页面有很多重组件

复制代码
<template v-for="item in 100">
            <sub-home-page :key="item" v-if="defer(item)"></sub-home-page>
        </template>

2.在created钩子中使用requestAnimationFrame对count进行赋值

复制代码
let that = this
        function updataFrame() {
            that.count++;
            if(that.count >= this.components) return 
            that.reqId = requestAnimationFrame(updataFrame);
        }
        updataFrame();

3.使用计算属性,来控制组件是否渲染

复制代码
defer(){
            return function(n){
                return this.count >= n;
            }
        }

4.在页面销毁的时候,取消requestAnimationFrame

复制代码
destroyed(){
        cancelAnimationFrame(that.reqId)
    },

Vue3版本:

首页模拟100个重组件

复制代码
<template>
    <div class="index">
        <div v-for="item in 100" :key="item">
            <sub-index v-if="defer(item)"></sub-index>
        </div>
    </div>
</template>

<script setup>
import subIndex from "./components/subIndex.vue";
import { useDefer } from "/src/utils/useDefer.js";
const defer = useDefer();
</script>

<style lang="less" scoped>
.index{
    width: 100%;
    height: 100%;
    overflow: auto;
    display: grid;
    grid-template-columns: repeat(3, fr);
    grid-gap: 0.1em;
}
</style>

子组件(重组件)

复制代码
<template>
    <div class="subHomePage">
        <div class="item" v-for="item in 5000" :key="item">
        </div>
    </div>
</template>

<script setup>

</script>
<style scoped lang="less">
.subHomePage{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    border: 3px solid red;
    .item{
        width: 5px;
        height: 3px;
        background: #ccc;
        margin: 0.1em;
    }
}
</style>

useDefer.js文件

复制代码
import { ref, onUnmounted } from "vue";
export function useDefer(maxCount = 100){
    let count = ref(0);
    let reqId = null;
    function updataFrame() {
        count.value++;
        if(count.value >= maxCount) return 
        reqId = requestAnimationFrame(updataFrame);
    }
    updataFrame();

    onUnmounted(() => {
        cancelAnimationFrame(reqId)
    })

    return function (n){
        return count.value >= n;
    }
}
相关推荐
山川绿水4 分钟前
Ubuntu22.04更新Openssh至9.9p2无法正常连接,报错解决
服务器·web安全·网络安全
古希腊数通小白(ip在学)15 分钟前
HCIA实现不同vlan间的通信
linux·服务器·网络
星辰离彬29 分钟前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
开开心心就好41 分钟前
电脑息屏工具,一键黑屏超方便
开发语言·javascript·电脑·scala·erlang·perl
江号软件分享42 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
web守墓人2 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
小苹果13572 小时前
阿里云mysql数据丢失,如何通过服务器备份在其他服务器上恢复数据,并获取mysql丢失数据,完成mysql数据恢复
服务器·mysql·阿里云
Savior`L2 小时前
CSS知识复习5
前端·css
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器