unjs / unhead

Unhead is the any-framework document head manager built for performance and delightful developer experience.
https://unhead.unjs.io
MIT License
589 stars 39 forks source link

`beforeInit` is running server-side even when the `trigger` is set to `client` #351

Closed enkot closed 3 months ago

enkot commented 3 months ago

Environment

Reproduction

https://stackblitz.com/edit/github-yhnmge-s1db7e?file=app.vue

Describe the bug

Currently beforeInit is always running server-side even if the trigger is set to client, so this example from the docs doesn't work in SSR:

const { gtag } = useScript<GoogleTag>('https://www.google-analytics.com/analytics.js', {
  beforeInit() {
    // Google Analytics Setup
    window.dataLayer = window.dataLayer || []
    window.gtag = function gtag(...p) { window.dataLayer.push(p) }
    window.gtag('js', new Date())
    window.gtag('config', options.id)
  },
  use() {
    return { gtag: window.gtag }
  }
})

I suggest running beforeInit on the server side only if the trigger is set to server or on the client only.

Additional context

No response

Logs

No response

harlan-zw commented 3 months ago

Thanks! Should be fixed in v1.9.11

enkot commented 3 months ago

@harlan-zw Unfortunately it still doesn't work as expected( You can check this repro https://stackblitz.com/edit/github-yhnmge-zfah8i?file=app.vue If you run it you will see in the console:

2. after beforeInit
1. beforeInit

Expected:

1. beforeInit
2. after beforeInit

Looks like beforeInit is running in the async context for some reason 👀

harlan-zw commented 3 months ago

This may be a documentation/usage issue from here, beforeInit should only run if the script is actually going to be loaded, so it's executed right before the script tag is inserted.

In Nuxt's case that's after the hydration occurs as the DOM render is indeed async.

Would you mind providing some context on the issue you're having, maybe there's some logic I've overlooked.

enkot commented 3 months ago

You are right, makes sense, I was using it incorrectly :) Thank you for the explanation! Closing this issue.