Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add scripts into the head tag when angular component has loaded

I have a script tag that has a skype web control cdn in it, the script tag has been inserted in the head of my index.html, now the script tag is called before the component I need it in has loaded, any ideas on how I can reference this script in my component?

like image 517
Smokey Dawson Avatar asked Oct 25 '17 03:10

Smokey Dawson


2 Answers

I've figured it out, what you need to do is dynamically create the script tag and then append it to the head of your document:

export class Component {

//...

loadScript() {
  let node = document.createElement('script'); // creates the script tag
  node.src = ''; // sets the source (insert url in between quotes)
  node.type = 'text/javascript'; // set the script type
  node.async = true; // makes script run asynchronously
  node.charset = 'utf-8';
  // append to head of document
  document.getElementsByTagName('head')[0].appendChild(node); 
}

ngOnInit{
  loadScript();
}
like image 156
Smokey Dawson Avatar answered Nov 14 '22 23:11

Smokey Dawson


script tag is called before the component I need it in has loaded, any ideas on how I can reference this script in my component

Most script tags export a global variable. E.g React $ _ etc. Read the docs on the lib and use the global variable they export.

like image 34
basarat Avatar answered Nov 14 '22 23:11

basarat