How to add external JS scripts to VueJS Components?

346,150

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);
    });
  }
Share:
346,150

Related videos on Youtube

Gijo Varghese
Author by

Gijo Varghese

Updated on February 17, 2022

Comments

  • Gijo Varghese
    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
    Gijo Varghese almost 7 years
    These scripts are from paypal and stripe. I can't download the put the file locally
  • Gijo Varghese
    Gijo Varghese almost 7 years
    These scripts are from paypal and stripe. I can't download the put the file locally
  • ba_ul
    ba_ul almost 7 years
  • Barlas Apaydin
    Barlas Apaydin about 6 years
    created() method can not get document, use mounted() instead
  • Yogi
    Yogi almost 5 years
    the link is broken
  • minimallinux
    minimallinux over 4 years
    You can download the external scripts, view source, copy/paste in to your own file.
  • Duncan Jones
    Duncan Jones over 4 years
    @minimallinux In the case of Stripe and Paypal, that will violate PCI-DSS. So don't do that.
  • danbars
    danbars about 4 years
    Once a script is loaded it is already in memory. Removing it from the dom does not remove its footprint.
  • ADM-IT
    ADM-IT about 4 years
    >> "Where do you place this code?" : It is in components section in your vuejs component.
  • Marius
    Marius almost 4 years
    Using 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
    bigwolk almost 4 years
    What 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
    matth over 3 years
    Can 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 to window?
  • bgrand-ch
    bgrand-ch about 3 years
    Works great, thanks! Additional tip with Webpack: require('module-name/file-name.js')
  • Ralph Bolton
    Ralph Bolton almost 3 years
    This 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
    Philipp Mochine almost 3 years
    Side-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
    Mekanic almost 3 years
    What file would this Vue.loadScript() be located in? Is the the App.vue file?
  • PHP.Newbie
    PHP.Newbie almost 3 years
    Hello! 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
    johnpitchko almost 3 years
    Thanks for this! Can anyone explain how/why this works? Learning Vue so am quite curious.
  • Egor Dudyak
    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
    Jauhien Parmon over 2 years
    @PHP.Newbie have you found solution to this problem with a local script?
  • Tarun Jain
    Tarun Jain over 2 years
    this worked for me thanks
  • zardilior
    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
    Taha Malik about 2 years
    Probably in main.js file