Hydration issue when rendering dynamic head element
See original GitHub issueDescribe the bug
When using the @sveltejs/adapter-static
and appending a script tag with application/ld+json type to svelte:head, it won’t show up in the build version of your site/app. It shows up correctly when you’re developing, but npm run build
loses it from head tag.
Code sample:
<script>
const item_title = 'Hello world!';
const schema = {
"@context": "http://schema.org",
"@type": "Article",
"@name": item_title
};
</script>
<svelte:head>
{@html '<script type="application/ld+json">' + JSON.stringify(schema) + '</script>'}
</svelte:head>
To Reproduce Append script tag with application/ld+json attribute on svelte:head and build/export site using static adapter.
Expected behavior Added script tag / ld json schema should be visible in head tag after exporting the site as static.
Information about your SvelteKit Installation:
Diagnostics
System: OS: Windows 10 10.0.18363 CPU: (4) x64 Intel® Core™ i5-4690K CPU @ 3.50GHz Memory: 2.39 GB / 7.95 GB
Binaries: Node: 15.12.0 - C:\Program Files\nodejs\node.EXE npm: 7.6.3 - C:\Program Files\nodejs\npm.CMD
Browsers: Chrome: 89.0.4389.114 Edge: Spartan (44.18362.449.0) Internet Explorer: 11.0.18362.1
npmPackages: @sveltejs/kit: next => 1.0.0-next.74 svelte: ^3.29.0 => 3.37.0 vite: ^2.1.0 => 2.1.5
Static adapter.
Severity Mediumish
Issue Analytics
- State:
- Created 2 years ago
- Comments:14 (5 by maintainers)
Top GitHub Comments
Just chiming in as I’m facing similar issues. As a recap, in my understanding the current state seems to be:
This is the most intuitive approach:
To make it work,
preprocess({ preserve: ['ld+json'] })
has to be set insvelte.config.js
. (Might be addressed in https://github.com/sveltejs/svelte-preprocess/issues/305 ?!)Unfortunately there is a huge downside: the schema object cannot be created dynamically. To address this problem, there is this workaround:
Now TypeScript is giving me pretty weird errors for the whole file (see screenshot) and Svelte Prettier is doing strange stuff too (converting the script tag to something like
[...]tion/ld+json" ✂prettier:content✂="JHsgSlNPTi5zdHJp[...]
).Though, someone on Stack Overflow found another workaround to keep TypeScript and Prettier happy:
This seems to do the trick, but looks and feels rather hacky.
BUT, again there is an issue: Now the JSON-LD script tag is included twice in the header. Even worse, the initial one won’t go away when navigating your website. That means
Can someone verify that the dynamic tag is included twice (and one of them doesn’t update)? What can we do to solve this?
A work around for this for anyone using google structured data, is to include it the body and not the head, since google doesn’t mind: https://www.youtube.com/watch?v=lI6EtxjoyDU&t=94s