How to add external JS scripts to VueJS Components?
Solution 1
A simple and effective way to solve this, it's by adding your external script into the vue mounted()
of your component. I will illustrate you with the Google Recaptcha script:
<template>
.... your HTML
</template>
<script>
export default {
data: () => ({
......data of your component
}),
mounted() {
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
document.head.appendChild(recaptchaScript)
},
methods: {
......methods of your component
}
}
</script>
Source: https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8
Solution 2
I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.
Found this plugin, it's a clean way to add external scripts both via CDN and from static files https://www.npmjs.com/package/vue-plugin-load-script
// local files
// you have to put your scripts into the public folder.
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")
// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")
Solution 3
using webpack and vue loader you can do something like this
it waits for the external script to load before creating the component, so globar vars etc are available in the component
components: {
SomeComponent: () => {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
script.onload = () => {
resolve(import(someComponent))
}
script.async = true
script.src = 'https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places'
document.head.appendChild(script)
})
}
},
Solution 4
UPDATE: This no longer works in Vue 3. You will receive this error:
VueCompilerError: Tags with side effect ( and ) are ignored in client component templates.
If you are trying to embed external js scripts to the vue.js component template, follow below:
I wanted to add a external JavaScript embed code to my component like this:
<template>
<div>
This is my component
<script src="https://badge.dimensions.ai/badge.js"></script>
</div>
<template>
And Vue showed me this error:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.
The way I solved it was by adding type="application/javascript"
(See this question to learn more about MIME type for js):
<script type="application/javascript" defer src="..."></script>
You may notice the defer
attribute. If you want to learn more watch this video by Kyle
Solution 5
This can be simply done like this.
created() {
var scripts = [
"https://cloudfront.net/js/jquery-3.4.1.min.js",
"js/local.js"
];
scripts.forEach(script => {
let tag = document.createElement("script");
tag.setAttribute("src", script);
document.head.appendChild(tag);
});
}
Related videos on Youtube
Gijo Varghese
Updated on February 17, 2022Comments
-
Gijo Varghese about 2 years
I've to use two external scripts for the payment gateways.
Right now both are put in the
index.html
file.However, I don't want to load these files at the beginning itself.
The payment gateway is needed only in when user open a specific component (
using router-view
).Is there anyway to achieve this?
Thanks.
-
Gijo Varghese almost 7 yearsThese scripts are from paypal and stripe. I can't download the put the file locally
-
Gijo Varghese almost 7 yearsThese scripts are from paypal and stripe. I can't download the put the file locally
-
ba_ul almost 7 yearsDo these wrappers solve your problem? github.com/matfish2/vue-stripe and github.com/khoanguyen96/vue-paypal-checkout
-
Barlas Apaydin about 6 years
created()
method can not get document, usemounted()
instead -
Yogi almost 5 yearsthe link is broken
-
minimallinux over 4 yearsYou can download the external scripts, view source, copy/paste in to your own file.
-
Duncan Jones over 4 years@minimallinux In the case of Stripe and Paypal, that will violate PCI-DSS. So don't do that.
-
danbars about 4 yearsOnce a script is loaded it is already in memory. Removing it from the dom does not remove its footprint.
-
ADM-IT about 4 years>> "Where do you place this code?" : It is in components section in your vuejs component.
-
Marius almost 4 yearsUsing variables defined by the script afterwards, even with defer set to false, doesn't work. Example: load api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js mapboxgl.accessToken = 123. Had to use vue-plugin-load-script .then() for this to work.
-
bigwolk almost 4 yearsWhat if you have to use this component several times? You will have script loaded multiple times. In case of google scripts it will throw warnings in your console.
-
matth over 3 yearsCan you explain what's going on with
import(someComponent)
? Does the script you're loading have to be defined as an es module? Does this not work if you are importing a script that attaches itself towindow
? -
bgrand-ch about 3 yearsWorks great, thanks! Additional tip with Webpack:
require('module-name/file-name.js')
-
Ralph Bolton almost 3 yearsThis is a good way to include external libraries that you don't control and can't include directly. To access constructors and functions within them, without the Vue compiler complaining, see stackoverflow.com/a/62617268/917444
-
Philipp Mochine almost 3 yearsSide-question: Does it make sense to add the attribute "defer"? I guess not because the website is already loaded, but maybe it still makes sense... Any idea?
-
Mekanic almost 3 yearsWhat file would this Vue.loadScript() be located in? Is the the App.vue file?
-
PHP.Newbie almost 3 yearsHello! I tried this solution. I want to load a script from project src/assets/js/ folder but it has error uncaught SyntaxError: Unexpected token '<'. But when I try to load from CDN it has no error. I am new to Vue and I used vue-cli to create the project. TIA
-
johnpitchko almost 3 yearsThanks for this! Can anyone explain how/why this works? Learning Vue so am quite curious.
-
Egor Dudyak almost 3 years@mejiamanuel57 What if I will reuse such vue component? Will each one add same <script> tag in document head?
-
Jauhien Parmon over 2 years@PHP.Newbie have you found solution to this problem with a local script?
-
Tarun Jain over 2 yearsthis worked for me thanks
-
zardilior about 2 years@marius you should add an onLoad event listener and event handler to that script. Meaning a function that runs when that scripts onLoad event triggers.
-
Taha Malik about 2 yearsProbably in main.js file