Reputation: 11249
I'm adding a simple script block to a simple aurelia view:
<template>
<script type="text/javascript">
alert('Hello!');
</script>
</template>
The script is never run, even though the view is rendered correctly and I can see that the script block does appear in the DOM.
I have also tried dynamically inserting a script block via the viewModel and also tried with:
<script type="text/javascript" src="http://blah"></script>
I understand it's not best practice to do this, but I'm trying to integrate a third party widget that will then render an iframe. The alert shown above is just a simple way of the verifying the issue that I'm seeing.
The real life scenario is as follows:
The following is returned:
<script type='text/javascript' language='JavaScript'
src='https://secure.na1.echosign.com/public/embeddedWidget? ` wid=CBFCIBAA3AAABLblqZhBU33GaMRZ2lMelHKzti7RkanxMP5v- uW_f8CEiKoopNNofJWyXhmE56Su3HTbY*&token=CBNCKBAAHBCAABAARNiZ7Yba0h7dnLaQRBAdTdH9UrJZKryP' />
I need to append this to the DOM and have it execute. I am working around this issue by calling the above url via fetch and then I exec the response, but it seems like a tedious/hacky way of doing it.
Upvotes: 12
Views: 3392
Reputation: 10887
I would recommend adapting the solution provided in this answer: Use JS variable to set the src attribute for <script> tag.
In your VM's bind
or attached
method (most likely):
let scriptURL = api.getURL();
let scriptElement = document.createElement('script');
scriptElement.src = scriptURL;
scriptElement.onload = () => {
// do anything you need to do here, or call a VM method
this.someVMMethod();
};
this.scriptElementInHead = document.querySelector('head').appendChild(scriptElement);
If need be, you can even remove the script element by keeping a reference to it and removing it from the head element when the component is being unloaded in the unbind
or detached
methods.
detached() {
document.querySelector('head').removeChild(this.scriptElementInHead);
}
Upvotes: 6