Skip to content

Commit

Permalink
perf(scripts): process triggers async on animation frames
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Jun 2, 2024
1 parent a1d38fa commit 325cbd3
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/unhead/src/composables/useScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,17 @@ export function useScript<T extends Record<symbol | string, any>>(_input: UseScr

const proxy = { value: (!head.ssr && options?.use?.()) || {} as T }
const loadPromise = new Promise<T>((resolve, reject) => {
const emit = (api: T) => requestAnimationFrame(() => resolve(api))
const _ = head.hooks.hook('script:updated', ({ script }) => {
if (script.id === id && (script.status === 'loaded' || script.status === 'error')) {
if (script.status === 'loaded') {
if (typeof options.use === 'function') {
const api = options.use()
api && resolve(api)
api && emit(api)
}
// scripts without any use() function
else {
resolve({} as T)
emit({} as T)
}
}
else if (script.status === 'error') {
Expand Down Expand Up @@ -98,7 +99,7 @@ export function useScript<T extends Record<symbol | string, any>>(_input: UseScr
else if (trigger instanceof Promise)
trigger.then(script.load)
else if (typeof trigger === 'function')
trigger(script.load)
trigger(async () => script.load())

// 3. Proxy the script API
const instance = new Proxy<{ value: T }>(proxy, {
Expand Down

0 comments on commit 325cbd3

Please sign in to comment.