wrahim
wrahim

Reputation: 1168

How to load cdn and access it's objects in Vue?

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.

Upvotes: 3

Views: 3889

Answers (2)

David D.
David D.

Reputation: 567

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.

Upvotes: 2

Hammerbot
Hammerbot

Reputation: 16344

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/

Upvotes: -1

Related Questions