How to use nuxt head only in client?

982 Views Asked by At

I have script which depends on a window attribute to be loaded:

sync head() {
    if (window.loadScript) { // window is not defined
      return {
        script: [
          {
            src: "https://some-api.com/min.js",
            type: "text/javascript",
     
            callback: function () {
              console.log("loaded")
            },
          },
        ],
      }
    }
  },

This results in: window is not defined error.

If this is not possible, whats the alternative?

1

There are 1 best solutions below

2
On

Try a conditional process.client as proposed here.

Or use your code in a client-side plugin only approach (far better): https://nuxtjs.org/docs/directory-structure/plugins#client-or-server-side-only

Also, I recommend not using CDNs but rather NPM directly so that you can import it without any latency and being able to update it rather quickly without manual intervention or any step error-prone.