vike icon indicating copy to clipboard operation
vike copied to clipboard

Add `<script>` to only one/some pages

Open brillout opened this issue 11 months ago • 5 comments

Description

Adding a <script> tag globally is easy with +Head. But using +Head doesn't work for adding a <script> tag to only one page, because +Head isn't applied upon client-side navigation.

Potential solutions:

  1. New +scripts setting
  2. Support +Head.shared.ts
  3. Also apply +Head upon client-side navigation, while adding a new HTML-only setting +metadata that is meant for bots & browsers.
    • Mixing high-level props (e.g. description) and low-level props (e.g. og.description).
    • Isn't it a DX paper cut that +title doesn't live in +metadata? (Since +metadata is server-only but the title needs to updated upon client-side navigation.)
    • See also: https://github.com/Blankeos/vike-metadata/issues/9.

brillout avatar Mar 03 '25 12:03 brillout

I am interested in this feature to support structured data in Google search results on a per-page basis, but it's not currently a super high priority for me.

nickdichev avatar Jul 03 '25 03:07 nickdichev

@nickdichev It's a SEO tag, so can use +Head as usual. I've recently updated https://vike.dev/Head to further explain this. You can then also use useConfig() inside your components.

brillout avatar Jul 03 '25 07:07 brillout

Thanks Rom that makes sense. I thought the limitation around the head value on initial navigation would be an issue, but it makes sense in the context of how a crawler would access my website

nickdichev avatar Jul 03 '25 17:07 nickdichev

HI @brillout, just coming back to thinking about this. One problem I'm having with +Head for structured data is that (from what I can tell) the head setting does not get access to pageContext. Two use cases that I have that require pageContext to generate data in the head:

  1. Use data fetched in +data to populate a Review structured context object (https://developers.google.com/search/docs/appearance/structured-data/review-snippet)
  2. I would like to add a noindex on some pages, depending on the number of results in a list fetched in +data

my idea is to use +onCreatePageContext.server.js to hook into and push the markup into the head. I'm curious if there's a good way to do this?

nickdichev avatar Jul 16 '25 02:07 nickdichev

@nickdichev usePageContext() also works for the +Head component (same as +Page and +Layout). ~~I'll update the docs to mention this~~ Done: docs updated.

brillout avatar Jul 16 '25 06:07 brillout