Set SSR parameter to false to run the script on client only:
(note this needs to be confirm, possibly is wrong)
plugins: [{ src: ‘~/plugins/vue-gallery.js’, ssr: false }]
If you want to add a script tag before closing the
instead of
tag, you can do it by adding a body: true.
script: [
{
src: “script url”,
body: true,
},
],
You can also add async, cross-origin attributes to a script tag like this.
This setup solves the issues of running the script in certain pages, in addition to that it allows to execute code that depends on the third party script only after the script is loaded.
This is an example posted by a user on the Nuxt issue board for dynamically loading a script. The key takeaway is checking the process.server value. By using ‘defer’ is generally a replacement for putting scripts in the body and remaining non-blocking.
export default {
mounted() {
// check the script is running in the client
if(process.server) return;
// and that has not run before
if (!window.<script defined variable>)
const script = document.createElement("script");
script.onload = this.onScriptLoaded;
script.type = "text/javascript";
script.src = "script url";
document.head.appendChild(script);
} else {
this.onScriptLoaded();
}
},
methods: {
onScriptLoaded(event = null) {
if (event) {
console.log("Was added");
} else {
console.log("Already existed");
}
... your code goes here...
}
}
}