How to load external scripts dynamically in Angular?

前端 未结 15 751
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:48

I have this module which componentize the external library together with additional logic without adding the

15条回答
  •  抹茶落季
    2020-11-22 07:07

    You can load multiple scripts dynamically like this in your component.ts file:

     loadScripts() {
        const dynamicScripts = [
         'https://platform.twitter.com/widgets.js',
         '../../../assets/js/dummyjs.min.js'
        ];
        for (let i = 0; i < dynamicScripts.length; i++) {
          const node = document.createElement('script');
          node.src = dynamicScripts[i];
          node.type = 'text/javascript';
          node.async = false;
          node.charset = 'utf-8';
          document.getElementsByTagName('head')[0].appendChild(node);
        }
      }
    

    and call this method inside the constructor,

    constructor() {
        this.loadScripts();
    }
    

    Note : For more scripts to be loaded dynamically, add them to dynamicScripts array.

提交回复
热议问题