mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 23:22:02 +00:00
feat: extract useObserver
This commit is contained in:
parent
85b4d6932b
commit
624188a7cf
@ -14,6 +14,7 @@ import { onNuxtReady } from '../composables/ready'
|
||||
import { navigateTo, useRouter } from '../composables/router'
|
||||
import { useNuxtApp, useRuntimeConfig } from '../nuxt'
|
||||
import { cancelIdleCallback, requestIdleCallback } from '../compat/idle-callback'
|
||||
import { useObserver } from "../utils"
|
||||
|
||||
// @ts-expect-error virtual file
|
||||
import { nuxtLinkDefaults } from '#build/nuxt.config.mjs'
|
||||
@ -403,49 +404,6 @@ function applyTrailingSlashBehavior (to: string, trailingSlash: NuxtLinkOptions[
|
||||
}
|
||||
|
||||
// --- Prefetching utils ---
|
||||
type CallbackFn = () => void
|
||||
type ObserveFn = (element: Element, callback: CallbackFn) => () => void
|
||||
|
||||
function useObserver (): { observe: ObserveFn } | undefined {
|
||||
if (import.meta.server) { return }
|
||||
|
||||
const nuxtApp = useNuxtApp()
|
||||
if (nuxtApp._observer) {
|
||||
return nuxtApp._observer
|
||||
}
|
||||
|
||||
let observer: IntersectionObserver | null = null
|
||||
|
||||
const callbacks = new Map<Element, CallbackFn>()
|
||||
|
||||
const observe: ObserveFn = (element, callback) => {
|
||||
if (!observer) {
|
||||
observer = new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const callback = callbacks.get(entry.target)
|
||||
const isVisible = entry.isIntersecting || entry.intersectionRatio > 0
|
||||
if (isVisible && callback) { callback() }
|
||||
}
|
||||
})
|
||||
}
|
||||
callbacks.set(element, callback)
|
||||
observer.observe(element)
|
||||
return () => {
|
||||
callbacks.delete(element)
|
||||
observer!.unobserve(element)
|
||||
if (callbacks.size === 0) {
|
||||
observer!.disconnect()
|
||||
observer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const _observer = nuxtApp._observer = {
|
||||
observe
|
||||
}
|
||||
|
||||
return _observer
|
||||
}
|
||||
|
||||
function isSlowConnection () {
|
||||
if (import.meta.server) { return }
|
||||
|
Loading…
Reference in New Issue
Block a user