Javascript – How to add external JS scripts to VueJS Components


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?


Best Solution

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:

   .... your HTML

  export default {
    data: () => ({ of your component
    mounted() {
      let recaptchaScript = document.createElement('script')
      recaptchaScript.setAttribute('src', '')
    methods: {
      ......methods of your component