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;
    }
}
相关推荐
java小吕布6 小时前
CentOS 7 服务器性能监控实战指南
linux·服务器·centos
程序员爱钓鱼6 小时前
Node.js 编程实战:图像与文件上传下载
前端·后端·node.js
椰子今天很可爱6 小时前
仿照muduo库实现一个高并发服务器
linux·服务器·c++
yesyesyoucan7 小时前
安全工具集:一站式密码生成、文件加密与二维码生成解决方案
服务器·mysql·安全
小豆子范德萨7 小时前
cursor连接远程window服务器的WSL-ubuntu
运维·服务器·ubuntu
kong79069287 小时前
环境搭建-运行前端工程(vue)
前端·前端环境
谷歌开发者7 小时前
Web 开发指向标|开发者工具 AI 辅助功能的 5 大实践应用
前端·人工智能
晚烛13 小时前
实战前瞻:构建高可靠、强协同的 Flutter + OpenHarmony 智慧教育平台
javascript·flutter·html
Xの哲學13 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
快乐肚皮13 小时前
一文了解XSS攻击:分类、原理与全方位防御方案
java·前端·xss