fix(nuxt): make `onNuxtReady` safe to run on server-side (#18706)

This commit is contained in:
Daniel Roe 2023-02-02 05:27:48 -08:00 committed by GitHub
parent cce4df1cb9
commit cb0860ba6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 8 additions and 2 deletions

View File

@ -17,3 +17,7 @@ export default defineNuxtPlugin(() => {
```
It is 'safe' to run even after your app has initialized. In this case, then the code will be registered to run in the next idle callback.
::alert
`onNuxtReady` only runs on the client-side.
::

View File

@ -1,7 +1,7 @@
// Polyfills for Safari support
// https://caniuse.com/requestidlecallback
export const requestIdleCallback: Window['requestIdleCallback'] = process.server
? undefined as any
? (() => {}) as any
: (globalThis.requestIdleCallback || ((cb) => {
const start = Date.now()
const idleDeadline = {
@ -12,5 +12,5 @@ export const requestIdleCallback: Window['requestIdleCallback'] = process.server
}))
export const cancelIdleCallback: Window['cancelIdleCallback'] = process.server
? null as any
? (() => {}) as any
: (globalThis.cancelIdleCallback || ((id) => { clearTimeout(id) }))

View File

@ -2,6 +2,8 @@ import { useNuxtApp } from '../nuxt'
import { requestIdleCallback } from '../compat/idle-callback'
export const onNuxtReady = (callback: () => any) => {
if (process.server) { return }
const nuxtApp = useNuxtApp()
if (nuxtApp.isHydrating) {
nuxtApp.hooks.hookOnce('app:suspense:resolve', () => { requestIdleCallback(callback) })