0

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?

oemera
  • 3,223
  • 1
  • 19
  • 33

1 Answers1

0

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.

kissu
  • 40,416
  • 14
  • 65
  • 133
  • 1
    Using `process.client` will successfully run the code inside the `if` on the client, but won't add the script tag however. It's not in the DOM tree, not sure why. Without the condition it's loaded. This module has no NPM package unfortunately. Plugins are always global and I would need to load the script "by hand" right? I want the script to only load on one component and only if a certain condition is true, to avoid unnecessary traffic. – oemera Nov 16 '22 at 07:55
  • @oemera I'm not sure where is `sync head` located tbh. Here [are ways](https://stackoverflow.com/a/67535277/8816585) to achieve that one. What is the given module? There is a CDN or it's some homemade script? Loading it like you do makes it global too tbh, only a local `import` will load it from that given moment. Once your script is loaded, then it's part of your whole SPA and will not get removed. Unnecessary traffic? Your thing is hacky and quite heavy on top of that? Cannot embed it inside a `script` section, what is it really about? – kissu Nov 16 '22 at 12:40