0

I'm using Angular and need to call a third party script from a function inside another script tag.

For example:

In the index.html


  let showOnHomePage = () => {

  if (window.location.href === 'http://localhost:4100/') {

    ** I'm trying to run the scripts below conditionally. If taken out of the function the below scripts work. **

         <script> var _ctct_m = "my_numberic_key would go here"; </script>
         <script id="newScript" src="https://thewebsite.min.js" async defer></script>
  }
    
  }

  showOnHomePage();
</script>```


mwave317
  • 11
  • 6
  • Does this answer your question? [How do I include a JavaScript script file in Angular and call a function from that script?](https://stackoverflow.com/questions/44817349/how-do-i-include-a-javascript-script-file-in-angular-and-call-a-function-from-th) – mwilson Apr 09 '21 at 17:07

1 Answers1

0

You can create elements from code, including script tags:

function log(){console.log(stuff);}
function script(){
  let s=document.createElement("script");
  s.innerText="let stuff=10;";
  document.body.appendChild(s);
}
<button onclick="log()">Log</button><br>
<button onclick="script()">Script</button>

(try pressing Log, see error message, then Script and Log again)

The same should work with non-local source too, like

let s=document.createElement("script");
s.id="newScript";
s.src="https://thewebsite.min.js";
s.async=true;
s.defer=true;
document.body.appendChild(s);
tevemadar
  • 12,389
  • 3
  • 21
  • 49
  • Thanks for the response. This downloads the script but it doesn't run. – mwave317 Apr 09 '21 at 19:20
  • @mwave317 give it a try without `defer`, as it has a meaning when the page loads, and may cause problem afterwards. `async` feels less "dangerous", but you can try removing that too. – tevemadar Apr 09 '21 at 21:25
  • Thank you for the help. I got it to work with the async and the defer. The problem was it needed this . Above the script tag with the function that included the createElement("script"); – mwave317 Apr 12 '21 at 13:57