Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(scripts): safer lifecycle hooks onLoaded, onError #381

Merged
merged 1 commit into from
Aug 20, 2024

Conversation

harlan-zw
Copy link
Collaborator

@harlan-zw harlan-zw commented Aug 20, 2024

Currently we can wait for a script to load like so

const script = useScript('/script.js')
script.then(() => {
  // script loaded!
})

This provides a simple promise-based interface that is concise and fairly easy to work with, however, this has several issues:

  • Awaiting the script may brick the page if called at the wrong time
  • No way to de-register the callback
  • Bypasses any contextual lifecycle hooks such as Vue's component mounting
  • Promise handles use more memory, especially if they're staying open

To address this we move to a lifecycle register setup, where callbacks are provided to onLoaded and onError.

const script = useScript('/script.js')
// ✅ no promise handles left open, can't await as it's not a promise
const deregister = script.onLoaded(() => {
  // script loaded!
  // ✅ we can have this automatically hook into lifecycle events like Vue mounting
})
// ...
deregister() // ✅ we can deregister the callback

@harlan-zw harlan-zw merged commit 3fe9217 into main Aug 20, 2024
2 checks passed
@harlan-zw harlan-zw deleted the feat/scripts-lifecycle-hooks branch August 20, 2024 01:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant