How to add external JS scripts to VueJS Components? How to add external JS scripts to VueJS Components? vue.js vue.js

How to add external JS scripts to VueJS Components?


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


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 fileshttps://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")// cdnVue.loadScript("https://maps.googleapis.com/maps/api/js")


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)  }) }},