Home > Mobile >  Nuxt - render HTML only on server side
Nuxt - render HTML only on server side

Time:04-01

My page has a header, that I get from file located in server:

data() {
  return {
    headerHTML: ''
  };
},
fetch() {
  this.headerHTML = fs.readFileSync('./header.html', 'utf8');
}

I render header using v-html:

<div v-html="headerHTML"></div>
<div >
    <Nuxt />
</div> 

It works fine, but header is beeing sent from server to client twice - 1st time in HTML generated in server-side rendering process and 2nd time as a data "headerHTML" in Vue component. Header is large, so it affects performance. Is there a way to render HTML only on server, wihout sending data to client?

CodePudding user response:

AFAIK, there is no way to have it rendered only on the server because it's the main purpose of Nuxt (being isomorphic: server client).

There is probably some other way to make it a bit more performance efficient.

CodePudding user response:

I've figured it out.

I've created new Header component:

export default {
  render(createElement: CreateElement) {
    if (process.server) {
      const fs = process.server ? require('fs') : null;
      const file = fs.readFileSync('./header.txt', 'utf8');
      return createElement('div', { domProps: { innerHTML: f } });
    }
    return createElement('div', { domProps: { innerHTML: this.$el.innerHTML } });
  },
}

And I use it instead v-html in main component:

<Header />
<div >
    <Nuxt />
</div> 

In this way on the server side Nuxt loads file to variable, set html using innerHTML and returns the page to client (without header content stored in component data). On the client side Header component render what is already inside it.

  • Related