3

I have to load an external javascript file in order to have access to a certain object.

Normally the code is very simple:

<script src='https://example.com/example.js'></script>

<script>

  var instance = new ExampleObj.start({ container: 'element-id' });

</script>

<div id='element-id'></div>

How do I accomplish this in a .vue file?

This did not work:

export default {
  ...
  mounted() {
    const script = document.createElement('script')

    script.setAttribute('src', 'https://example.com/example.js')

    const start = document.createElement('script')

    start.text = `var instance = new ExampleObj.start({ container: 'element-id' });`

    document.body.appendChild(script)
    document.body.appendChild(start)
  }
  ...
}

The ^ above examples gives error: ExampleObj not defined, however if I try to access ExampleObj it shows up on the developer console with the start method working.

wrahim
  • 1,158
  • 4
  • 16
  • 33
  • Sounds like timing: the script tags get attached, but it takes some time for them to load. You could try using `onload` on them to indicate readiness. – Roy J Nov 10 '18 at 12:23
  • 1
    If you are indeed using nuxt, then use external resources noted in the docs https://nuxtjs.org/faq/ though think about grabbing the lib and having it local instead. – Lawrence Cherone Nov 10 '18 at 13:19

2 Answers2

2

Follow these steps:

  1. Add your CDN script in your index.html above vue.js scripts. I would put it right before head ending tag:

<script src='https://example.com/example.js'></script> </head>

  1. If you use webpack - add to externals so you can import it in your vue component.
  2. If you don't use webpack - access the JS object using window.ExampleObject in your mounted () function.
David D.
  • 557
  • 7
  • 20
-1

you should wait for the script to be loaded:

const script = document.createElement('script')

const start = document.createElement('script')

start.text = `console.log('jquery object', $('#app').text())`

script.onload = () => {
    document.body.appendChild(start)
}

script.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js')

document.body.appendChild(script)

You should set the src attribute after the onload event

From this question: Trying to fire the onload event on script tag

Here is a working jsFiddle I made: https://jsfiddle.net/jovmypnx/1/

Hammerbot
  • 15,696
  • 9
  • 61
  • 103