Skip to content

Instantly share code, notes, and snippets.

@MartinMalinda
Created August 8, 2021 11:37
Show Gist options
  • Save MartinMalinda/38e720983eac58e06bda5bdf9bdc6401 to your computer and use it in GitHub Desktop.
Save MartinMalinda/38e720983eac58e06bda5bdf9bdc6401 to your computer and use it in GitHub Desktop.
<script lang="ts">
import { useIntersectionObserver } from '@vueuse/core';
function onIdle(cb = () => {}) {
if ('requestIdleCallback' in window) {
window.requestIdleCallback(cb);
} else {
setTimeout(() => {
nextTick(cb);
}, 300);
}
}
export default {
props: {
renderOnIdle: Boolean,
},
setup(props) {
const shouldRender = ref(false);
const targetEl = ref();
const { stop } = useIntersectionObserver(
targetEl,
([{ isIntersecting }]) => {
if (isIntersecting) {
shouldRender.value = true;
stop();
}
}, {
rootMargin: '600px'
}
);
if (props.renderOnIdle) {
onIdle(() => {
shouldRender.value = true;
stop();
});
}
return { targetEl, shouldRender }
}
}
</script>
<template>
<div ref="targetEl">
<slot v-if="shouldRender" />
</div>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment