skip to Main Content

I am currently working on a NUXT application where there is a necessity to add some dynamic content inside <head> section of selected pages. The content that needs to get inserted into the pages <head> comes from a one time API response when the application initially starts (nuxtServerInit). This will in turn get stored in VUEX.The object structure looks like

[{
   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>"'
}]

So scripts should be injected/removed into <head> section of pages based on the configuration(ie content inside the key script should be placed inside <head>).
I had a research on this and I found that NUXT provides a head function which can be used inside a component/layout, the object returned by that function can be dynamically constructed based on page route name

//dynamically generate head scripts based on page route 
head () {
    return getScriptsForThisPage()        
  }

But the problem is that the key script contains scripts, external links, meta info which should be directly used inside the <head> tag. So those parsing logic needs to written inside function getScriptsForThisPage() in order to use NUXT head() function. It would have been convenient if we could directly put whatever inside script key to be appended to <head> tag.

Is there any better/smarter approach than this

Update – <head> should be filled (SEO purpose) before the page is mounted ,so we should not use client side DOM manipulation methods

2

Answers


  1. Have you aver tried basic DOM techniques such as ::

      document.head.appendChild
    

    and or ::

     document.head.removeChild
    

    built in function methods of adding and removing nodes from an existing node or a root element?

    That’s after you’ve pre-processed the JSON response and createdparsed the html tags to html elements.

    Login or Signup to reply.
    1. Since the application is getting data from nuxt server init, what you can do, is store that information as part of the internal nuxt state (say, pass that data via vuex) and update the head based on the page state.

    2. Alternatively you can leverage asyncdata (which is used to call a remote API before the page create). This is extremely useful for SSR to dynamically change the data before the page is created. This way you can set the head script based on whatever is set when asyncData has the configuration.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search