In my current project with NUXT application, I am facing a challenge with adding dynamic content to the <head>
section of specific pages. This content is generated from a one-time API response during the application initialization process (nuxtServerInit) and is then stored in VUEX. The structure of the object containing this content is as follows:
[{
pages:['index','home','..',....],
script:'<script>....</script><script>...</script>,<link href="someCss.css</link>"'
},
{
pages:['about','..',...],
script:'<script>....</script><script>...</script>,<link href="someOtherCss.css</link>"'
}]
On selected pages, the scripts should be injected or removed from the <head>
section based on the configuration (the content inside the key script should be placed inside <head>
). While researching a solution for this, I discovered that NUXT provides a head function that can be used within a component/layout, where the object returned by this function can be dynamically constructed based on the page's route name:
// dynamically generate head scripts based on the page route
head () {
return getScriptsForThisPage()
}
However, the challenge lies in properly parsing the content within the key script, which includes scripts, external links, meta information that should be directly inserted into the <head>
tag. This parsing logic needs to be implemented within the function getScriptsForThisPage()
in order to utilize NUXT's head() function effectively. It would be more convenient if we could directly append whatever is inside the script key to the <head>
tag.
Are there any better or smarter approaches to tackle this issue?
Update - The <head>
section needs to be filled for SEO purposes before the page is mounted, hence we should avoid using client-side DOM manipulation methods.