From 325cbd37066309ab90052504a40f40ddb3768a77 Mon Sep 17 00:00:00 2001 From: harlan Date: Sun, 2 Jun 2024 21:30:33 +1000 Subject: [PATCH] perf(scripts): process triggers async on animation frames --- packages/unhead/src/composables/useScript.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/unhead/src/composables/useScript.ts b/packages/unhead/src/composables/useScript.ts index a58ae015..9c54cd94 100644 --- a/packages/unhead/src/composables/useScript.ts +++ b/packages/unhead/src/composables/useScript.ts @@ -41,16 +41,17 @@ export function useScript>(_input: UseScr const proxy = { value: (!head.ssr && options?.use?.()) || {} as T } const loadPromise = new Promise((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') { @@ -98,7 +99,7 @@ export function useScript>(_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, {