
jstar
创建者
利用浏览器的 fps(每秒的帧数,每秒渲染多少张页面),每帧去渲染特定模块。形成逐帧渲染的状态,让页面先渲染一部分,展示出来,再慢慢渲染剩余的。
利用浏览器 requestAnimationFrame API,每帧执行时,匹配可渲染模块,让其渲染。
import { onUnmounted, ref } from "vue";
export const useDefer = (maxCount = 100) => {
const frameCount = ref(1); // 记录当前渲染了多少帧
let rafId: any; // 存requestAnimationFrame实例,以便销毁
function updateFrameCount() {
rafId = requestAnimationFrame(() => {
frameCount.value++;
if (frameCount.value >= maxCount) return; // 超过最大渲染数,停止
updateFrameCount();
});
}
updateFrameCount(); // 开启渲染
onUnmounted(() => {
cancelAnimationFrame(rafId); // 销毁实例
});
return function (n: number) {
return frameCount.value >= n; // 根据n(模块所属渲染帧次),判断其是否可以渲染,boolean
};
};<template>
<div class="wh100 wrap">
<template v-for="item in 100" :key="item">
<HeavyComp v-if="defer(item)"></HeavyComp>
</template>
</div>
</template>
<script setup lang="ts">
import HeavyComp from "./components/defer/HeavyComp.vue";
import { useDefer } from "@jstar-public-lib/utils";
const defer = useDefer(1000);
</script>
<style scoped>
.wrap {
display: flex;
flex-wrap: wrap;
}
</style>
创建者