Reputation: 1168
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
Reputation: 567
Follow these steps:
<script src='https://example.com/example.js'></script>
</head>
Upvotes: 2
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