Sometimes, we want to add external JavaScript scripts to Vue.js components.
In this article, we’ll look at how to add external JavaScript scripts to Vue.js components.
How to add external JavaScript scripts to Vue.js components?
To add external JavaScript scripts to Vue.js components, we can add a script element with document.createElement
.
For instance, we write
export default {
//...
mounted() {
const recaptchaScript = document.createElement("script");
recaptchaScript.setAttribute(
"src",
"https://www.google.com/recaptcha/api.js"
);
document.head.appendChild(recaptchaScript);
},
//...
};
to call document.createElement
with 'script'
to create a script element.
And then we call setAttribute
to set the src
property of it to the script’s URL.
Finally, we call document.head.appendChild
to append the script to the head element as its child.
Conclusion
To add external JavaScript scripts to Vue.js components, we can add a script element with document.createElement
.