How to load external scripts dynamically in Angular?

前端 未结 15 1088
被撕碎了的回忆
被撕碎了的回忆 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:00

    Hi you can use Renderer2 and elementRef with just a few lines of code:

    constructor(private readonly elementRef: ElementRef,
              private renderer: Renderer2) {
    }
    ngOnInit() {
     const script = this.renderer.createElement('script');
     script.src = 'http://iknow.com/this/does/not/work/either/file.js';
     script.onload = () => {
       console.log('script loaded');
       initFile();
     };
     this.renderer.appendChild(this.elementRef.nativeElement, script);
    }
    

    the onload function can be used to call the script functions after the script is loaded, this is very useful if you have to do the calls in the ngOnInit()

提交回复
热议问题